Sie sind auf Seite 1von 27

Lecture 6

Streams and Serialization

Stream

Is essentially a sequence of bytes, representing a flow of data from a source to a destination. Source or destination could be for example disk file, device or network socket.

Dealing with Streams

Any read or write is performed in three simple steps:


Step 1. Open the stream
you need to define some objects here

Step 2. Until there is more data, keep reading in a read, or writing in a write.
You need to use the methods of the objects defined in step1 to read the stream.

Step 3. Close the stream.

Java IO Package
The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java.

All these streams represent an input source and an output destination.


The stream in the java.io package supports many data such as primitives, Object, localized characters, etc.

Java IO Purposes and Features

The Java IO classes, which mostly consists of readers / writers, are addressing various purposes. That is why there are so many different classes. The purposes addressed are summarized below: File Access Network Access Buffering

Parsing
Reading and Writing Text (Readers / Writers) Reading and Writing Primitive Data (long, int etc.) Reading and Writing Objects

Input Streams

Reading text from the keyboard using Scanner class


Import - java.util.* library that includes the Scanner class Step1: define a Scanner object, sc or any name. To take input from the keyboard, use (System.in) Step2: use the Scanner object to get data

Step3: close the Scanner when finished using it!

Reading text from a file using Scanner class


Import : - java.util.* to use Scanner class - java.io.* to use File class Step1a: create a File object that points to your text file. Step1b: define a Scanner object, sc or any name. To take input from the text file, use the file object you created in Step2a Step2: use the Scanner object to get data Step3: close the Scanner when finished using it!

Note
for this code to work properly, we need to write some error handling code to handle the situation when the file is not found.

Common Scanner methods


input methods:
s = sc.next() s = sc.nextLine() i = sc.nextInt() Returns next token (i.e. "word). Returns an entire input line as a String. Returns next integer value. Returns next double value.

d = sc.nextDouble()

x = sc.nextXYZ() Returns value of type XYZ (primitive value if possible), where XYZ is one of BigDecimal,BigInteger,Boolean,Byte,Float, or Short.

test methods (used for error checking and loops):


b = sc.hasNext() b = sc.hasNextInt() True if another token is available to be read. True if another line is available to be read. True if another int is available to be read. b = sc.hasNextLine()

b = sc.hasNextDouble()
b = sc.hasNextXYZ()

True if another double is available to be read.


XYZ stands for one of the input types available above.

Getting input using BufferedReader and another input stream reader

The BufferedReader wraps another Reader and improves performance. Readers:


(1) (2)

InputStreamReader to get input from keyb. as bytes and translates it to characters FileReader to get input from files.

The BufferedReader provides a readLine method to read a line of text.

Note that InputStreamReader doesnt provide a readLine method.

Java also has a class called BufferedWriter that has a similar function for writing data.

Reading from keyboard Using Buffered Reader


Step1: open an input stream Step2: get data

Step3: close the input stream

reading input from a File using FileReader

Reading from File Using Buffered Reader

Step1: open an input stream Step2: get data Step3: close the input stream

reading input from keyboard using InputStreamReader

Output Streams

Writing text to a file using PrintWriter class


Import - java.io.* to use the PrintWriter class Step1a: create a File object that points to your text file. Step1b: create PrintWriter object that points to your text file. Step2: use the PrintWriter object to write text Step3: close the PrintWriter when finished using it!

Note

Any data in the aaa.txt file will be erased before writing the new data using println method. For this code to work, we need to write some error handling code to handle the situation when the file is not found.

Solution
Append Mode in File Writer FileWriter fw = new FileWriter(file, true);

or

PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outfilename", true)));

Summary

Classes to use Scanner BufferedReader


InputStreamReader FileReader
etc

Classes to use PrintWriter BufferedWriter


OutputStreamWrite FileWriter
etc

Source
Keyboard, File,
etc

Destination
Screen, File, etc

Summary
READING Scanner
Replace X with:

From Keyboard
Scanner in = new Scanner(X); myString = in.next(); myInt = in.nextInt(); //etc in.close(); System.in

From File

new File("C:/filename")

BufferedReader
Replace X with:

BufferedReader in = new BufferedReader(X); myString = in.readLine(); in.close(); new InputStreamReader(System.in) new FileReader("C:/filename")

WRITING PrintWriter
Replace X with:

To Screen
PrintWriter out = new PrintWriter(X); out.println("some text here"); out.close(); System.out

To File

new File("C:/filename")

BufferedWriter
Replace X with:

BufferedWriter out = new BufferedWriter(X); out.write(some text here"); out.close();


new outputStreamWriter(System.out)
OR instead of both classes, simply write:

new FileWriter("C:/filename")

System.out.println(some text here);

For More About Other Input / Output stream Classes

http://tutorials.jenkov.com/java-io/index.html

Exercise

Develop a simple Employee Class with 3 methods ( Save, Load and Print)
Save method saves employee data to a file. The file name is passed to the method as a parameter Load method loads employee data from a file. The file name is passed to the method as a parameter

Print Method prints employee data to the screen.

Serialization

Serializations and Deserialization

Object serialization

is the process of saving an object's state to a sequence of bytes.

Deserialization

is the process of rebuilding those bytes into a live object.

How to Serialize an object


1) To Serialize an object you must implement the serializable interface. implements Serializable { } 2) Create output stream FileOutputStreamf= new FileOutputStream(filename); 3) Create object output stream ObjectOutputStreamout = new ObjectOutputStream(f);

3-Serialize it out.writeObject(ObjectHere); 4-close the stream out.close();

How to Deserialize Object


1-create input stream FileinputStreamf= new FileinputStream(filename); 2-create object input stream ObjectinputStreamin= new ObjectinputStream(f); 3-DeSerialize it Object obj= in.readObject(); 4-Cast the object

YourClassName x = (YourClassName ) obj;


5-Close the stream. in.close();

END

Das könnte Ihnen auch gefallen