10 FileIO
10 FileIO
Objective
To
Text
Text I/O
Use
Use
the Scanner class to read strings and numeric values from a text file
}
catch(IOException ioe) { System.out.println(ioe.toString()); } finally { } if (output != null) output.close(); }
5
try {
File file = new File("scores.txt"); Scanner input = null; input = new Scanner(file); while (input.hasNextLine()) { String line = input.nextLine(); System.out.println( line);
}
} catch (IOException ioe) { System.out.println(ioe.toString()); } finally { } if (input != null) input.close(); }
Caution
Scanner scanner = new Scanner(file.txt);
Object I/O
ObjectOutputStream
ObjectInputStream
class allow you to read entire object back in from the file
Called Deserialization
10
Make the class whose object you want to save implement Serializable interface.
If this object is referring to objects of other classes, you have to make those classes also implement Serializable interface
Create a FileOutputStream object FileOutputStream fos = new FileOutputStream(data.dat); Create an ObjectOutputStream object ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.close();
11
Serialization
What
gets serialized
All primitive-type instance attributes All objects the instance attributes refer to
What
Static attributes
13
Transient keywords
Sometimes
you
can use the transient keyword to tell the JVM to ignore some attributes when writing the object to an object stream.
public class Customer implements Serializable { int id; String name; transient String password; }
14
a class is serializable, all its subclasses are serializable even if they do not explicitly declare implements Serializable
15
public class Person { // does not implement Serializable String name; String ssn; public Person() { name = ; ssn = ; } } public class Customer extends Person implements Serializable { double deposit; Course c1; }
Only
16
All instance attributes, that are not marked transient, are serialized
If an attribute is of value type, its value is serialized If an instance attribute is of reference type, the object this attribute refers to is also serialized and also any objects this object may refer to is also serialized.
So, serialization saves the entire object graph: all objects referenced by instance variables starting with the object being serialized.
18
JVM determines the objects class type and attempts to load the objects class If class is not found, an exception is thrown and deserialization fails New object is created in the memory but the constructor of the class is not called The objects non-transient instance attributes are given the values from the serialized state. Transient attributes are given the default values (null for references, 0 for numeric-types etc.) If the object has a non-serializable class somewhere up its inheritance tree, the constructor for that class is called along with any constructors above that
19