0% found this document useful (0 votes)
51 views

10 FileIO

This document discusses file input/output in Java, including: 1. Using PrintWriter and Scanner classes to write and read text files. 2. Serializing and deserializing Java objects to save and read entire object graphs to and from files using ObjectOutputStream and ObjectInputStream. 3. Key steps for serialization include making classes implement Serializable and writing/reading objects using ObjectOutputStream/ObjectInputStream. Transient fields are not serialized.

Uploaded by

balakbmm
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

10 FileIO

This document discusses file input/output in Java, including: 1. Using PrintWriter and Scanner classes to write and read text files. 2. Serializing and deserializing Java objects to save and read entire object graphs to and from files using ObjectOutputStream and ObjectInputStream. 3. Key steps for serialization include making classes implement Serializable and writing/reading objects using ObjectOutputStream/ObjectInputStream. Transient fields are not serialized.

Uploaded by

balakbmm
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 19

File Input/Output

Objective
To

learn how to read from and write to text files file

Text

can be read by a text editor like notepad, wordpad, etc.

Text I/O
Use

PrintWriter class to write strings and numeric values to a text file

Use

the Scanner class to read strings and numeric values from a text file

Writing Data Using PrintWriter


java.io.PrintWriter +PrintWriter(filename: String) +print(s: String): void +print(c: char): void +print(cArray: char[]): void +print(i: int): void +print(l: long): void +print(f: float): void +print(d: double): void +print(b: boolean): void Also contains the overloaded println methods. Also contains the overloaded printf methods. . Creates a PrintWriter for the specified file. Writes a string. Writes a character. Writes an array of character. Writes an int value. Writes a long value. Writes a float value. Writes a double value. Writes a boolean value. A println method acts like a print method; additionally it prints a line separator. The line separator string is defined by the system. It is \r\n on Windows and \n on Unix. The printf method was introduced in 3.6, Formatting Console Output and Strings.

public static void main(String[ ] args) { java.io.PrintWriter output ; try {

output = new java.io.PrintWriter(scores.txt);


// creates a file if it does not exist; //discards the current content if the file exists output.print("John T Smith "); output.print("Eric K Jones "); output.flush(); output.println(90); output.println(85);

}
catch(IOException ioe) { System.out.println(ioe.toString()); } finally { } if (output != null) output.close(); }
5

Reading Data Using Scanner


java.util.Scanner +Scanner(source: File) +Scanner(source: String) +close() +hasNext(): boolean +next(): String +nextByte(): byte +nextShort(): short +nextInt(): int +nextLong(): long +nextFloat(): float +nextDouble(): double +useDelimiter(pattern: String): Scanner Creates a Scanner that produces values scanned from the specified file. Creates a Scanner that produces values scanned from the specified string. Closes this scanner. Returns true if this scanner has another token in its input. Returns next token as a string. Returns next token as a byte. Returns next token as a short. Returns next token as an int. Returns next token as a long. Returns next token as a float. Returns next token as a double. Sets this scanners delimiting pattern.

public static void main(String[ ] args) {

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);

is treating the String file.txt as source, NOT the file file.txt

Object File Input/Output

Object I/O
ObjectOutputStream

class allows you to save an entire object to a file


Called Serialization

ObjectInputStream

class allow you to read entire object back in from the file
Called Deserialization

10

Steps to write an object to a file (Serialization)

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);

Write the student object


oos.writeObject(objectRef); // objectRef is the ref to the object being serialized

Close the ObjectOutputStream

oos.close();
11

Steps to read an object to a file (Deserialization)

Create a FileInputStream object


FileInputStream fis = new FileInputStream(students.dat);

Create an ObjectInputStream object


ObjectInputStream ois = new ObjectInputStream(fis);

Write the student object


ObjectClass o = (ObjectClass)( ois.readObject()); // ObjectClass is the class of the object being deserialized

Close the ObjectOutputStream ois.close();


12

Serialization
What

gets serialized

All primitive-type instance attributes All objects the instance attributes refer to
What

doesnt get serialized

Static attributes

13

Transient keywords
Sometimes

you may not want to serialize some attributes

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

Serialization and Inheritance


public class RentalItem implements Serializable { String title; int id; }
If

a class is serializable, all its subclasses are serializable even if they do not explicitly declare implements Serializable

15

Serialization and Inheritance


What if you try to serialize an object of the Student class?

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

attributes of subclass are serialized

16

But then, what happens when the student object is deserialized?


Q. What will be the value of the attributes ssn and name? A. Whatever the argument-less constructor of Person class initializes them to. Q. Is there any way to save the values of ssn and name attributes A. Serialize the Person class attributes separately and then deserialize them separately

Summary of what actually happens during Serialization

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

Summary of what happens during Deserialization?

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

You might also like