Lecture 6 Streams and Serialization
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.
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.
Java IO Package
The java.io package contains nearly every class you might ever need to perform input and output (I/O) in Java.
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
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.
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.
b = sc.hasNextDouble()
b = sc.hasNextXYZ()
InputStreamReader to get input from keyb. as bytes and translates it to characters FileReader to get input from files.
Java also has a class called BufferedWriter that has a similar function for writing data.
Step1: open an input stream Step2: get data Step3: close the input stream
Output Streams
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
Summary
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:
new FileWriter("C:/filename")
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
Serialization
Object serialization
Deserialization
END