0% found this document useful (0 votes)
2 views25 pages

Lecture 26 27 Binary Files(Object Streaming)

The document discusses I/O handling in Java, emphasizing the differences between text and binary files, with binary I/O being more efficient as it does not require encoding or decoding. It covers the use of various Java I/O classes, such as InputStream and OutputStream, for reading and writing binary data, as well as the concept of serialization and deserialization of objects. Additionally, it explains the Serializable interface and the rules governing serialization, including handling non-serializable fields and duplicate objects.

Uploaded by

awaismumtaz1406
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views25 pages

Lecture 26 27 Binary Files(Object Streaming)

The document discusses I/O handling in Java, emphasizing the differences between text and binary files, with binary I/O being more efficient as it does not require encoding or decoding. It covers the use of various Java I/O classes, such as InputStream and OutputStream, for reading and writing binary data, as well as the concept of serialization and deserialization of objects. Additionally, it explains the Serializable interface and the rules governing serialization, including handling non-serializable fields and duplicate objects.

Uploaded by

awaismumtaz1406
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Lecture – 26-27

Binary Files
How is I/O Handled in Java?
• A File object encapsulates the properties of a file or a path, but does not contain the methods for
reading/writing data from/to a file.
• In order to perform I/O, you need to create objects using appropriate Java I/O classes.
Scanner input = new Scanner(new File("temp.txt"));
System.out.println(input.nextLine());

PrintWriter output = new PrintWriter("temp.txt");


output.println("Java 101");
output.close();
2
Binary I/O does not involve encoding or decoding and
Text File vs. Binary File thus is more efficient than text I/O.

• Data stored in a text file are represented in human-readable form.


• Data stored in a binary file are represented in binary form. You
cannot read binary files.
• Binary files are designed to be read by programs.
– For example, the Java source programs are stored in text files and can be
read by a text editor, but the Java classes are stored in binary files and
are read by the JVM.
– The advantage of binary files is that they are more efficient to process
than text files.
Binary I/O
• Text I/O requires encoding and decoding.
• The JVM converts a Unicode to a file
specific encoding when writing a
character and converts a file specific
encoding to a Unicode when reading a
character.
• Binary I/O does not require conversions.
When you write a byte to a file, the
original byte is copied into the file. When
you read a byte from a file, the exact byte
in the file is returned.
Binary I/O Classes
The abstract InputStream is the root class for reading binary data, and the abstract
OutputStream is the root class for writing binary data

5
InputStream

6
OutputStream

7
FileInputStream/FileOutputStream
FileInputStream
DataInputStream
InputStream FilterInputStream
BufferedInputStream
ObjectInputStream
Object
FileOutputStream BufferedOutputStream

OutputStream FilterOutputStream DataOutputStream

ObjectOutputStream PrintStream

• FileInputStream/FileOutputStream associates a binary


input/output stream with an external file.
• All the methods in FileInputStream/FileOuptputStream are
inherited from its superclasses.
• Does not introduce new methods

8
FileInputStream

9
FileOutputStream

• If the file does not exist, a new file would be created.


• If the file already exists, the first two constructors would delete the current
contents in the file.
• To retain the current content and append new data into the file, use the last
two constructors by passing true to the append parameter.
10
Example
import java.io.*;
public class TestFile{
public static void main(String[] args) throws IOException{
FileOutputStream output = new FileOutputStream("temp.dat");
for(int i=0; i<10; i++){
output.write(i);
}
output.close();
FileInputStream input = new FileInputStream("temp.dat");
int value;
while((value = input.read())!= -1)
System.out.println(value + " ");

}
} 4-11
Object I/O
• DataInputStream/DataOutputStream enables you to perform I/O for
primitive type values and strings.
• ObjectInputStream/ObjectOutputStream enables you to perform I/O for
objects in addition for primitive type values and strings.
FileInputStream
DataInputStream
InputStream FilterInputStream
BufferedInputStream
ObjectInputStream
Object
FileOutputStream BufferedOutputStream

OutputStream FilterOutputStream DataOutputStream

ObjectOutputStream PrintStream
12
ObjectInputStream
ObjectInputStream extends InputStream and implements
ObjectInput and ObjectStreamConstants.

13
ObjectOutputStream
ObjectOutputStream extends OutputStream and implements
ObjectOutput and ObjectStreamConstants.

14
Using Object Streams
• You may wrap an ObjectInputStream/ObjectOutputStream on
any InputStream/OutputStream using the following
constructors:

// Create an ObjectInputStream
public ObjectInputStream(InputStream in)

// Create an ObjectOutputStream
public ObjectOutputStream(OutputStream out)

15
Example
import java.io.*;
public class ObjectStream{
public static void main(String[] args)throws IOException, ClassNotFoundException{
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("temp1.dat"));
output.writeUTF("Ali");
output.writeDouble(85.5);
output.writeObject(new java.util.Date());
output.close();

ObjectInputStream input = new ObjectInputStream(new FileInputStream("temp1.dat"));


String name = input.readUTF();
double score = input.readDouble();
java.util.Date date = (java.util.Date)(input.readObject());
System.out.println(name+" "+score+" "+ date);
input.close();

}
}
4-16
Using Object Streams
• readObject() may throw ClassNotFoundException
– JVM restores an object by first loading the class for the object.
• You have to read the data from the file in the same order and
format as they were written to the file.

4-17
The Serializable Interface
• Serialization in Java is a mechanism of writing the
state of an object into a byte-stream
• The reverse operation of serialization is called
deserialization where byte-stream is converted into
an object
• The serialization and deserialization process is
platform-independent,
– Object can be serialized on one platform and deserialize
it on a different platform.
• import java.io.Serializable
4-18
The Serializable Interface
• The Serializable interface is a marker interface
– It has no data member and method
• The Serializable interface must be implemented by the class
whose object needs to be persisted.
• The String class and all the wrapper classes implement
the java.io.Serializable interface by default.
java.math.BigInteger, java.math.BigDecimal, java.lang.String, java.lang.StringBuilder,
java.lang.StringBuffer, java.util.Date, and java.util.ArrayList
All implement Serializable interface

4-19
The Serializable Interface
• When a serializable object is stored, the class of the object is
encoded; this includes
– class name
– signature of the class
• serialVersionUID unique identifier that represents the signature of the class.
– Values of the object’s instance variables, and
– The closure of any other objects referenced by the object
• The values of the object’s static variables are not stored

4-20
Example of Serialization
import java.io.Serializable; import java.io.*;
public class Student implements Serializable{ class Persist{
public static void main(String args[]){
int id; try{
String name;
public Student(int id, String name) { Student s1 =new Student(211, “Ali”);
this.id = id; FileOutputStream fout=new FileOutputStream("f.txt");
this.name = name; ObjectOutputStream out=new ObjectOutputStream(fout);
} out.writeObject(s1);
} out.flush();
out.close();
System.out.println("success");
}catch(Exception e){System.out.println(e);}
}
}

4-21
Example of Deserialization

import java.io.*;
class Depersist{
public static void main(String args[]){
try{

ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));


Student s=(Student)in.readObject();
System.out.println(s.id+" "+s.name);
in.close();
}catch(Exception e){System.out.println(e);}
}
}

4-22
Serialization Rules
• Java Serialization with Inheritance
– If a Parent class implements Serializable interface then all its sub classes will also
be serializable
• Java Serialization with Aggregation
– If a class has a reference to another class, all the references must be Serializable
otherwise serialization process will not be performed
– In such case, NotSerializableException is thrown at runtime.
• Java Serialization with array or collection
– In case of array or collection, all the objects of array or collection must be
serializable. If any object is not serializable, serialization will be failed.

4-23
Serialization
• Nonserializable fields
– If an object is an instance of Serializable but contains nonserializable instance
data fields, can it be serialized?
– The answer is no.
– To enable the object to be serialized, mark these data fields with the transient
keyword to tell the JVM to ignore them when writing the object to an object
stream

When an object of the C class is serialized, only variable v1 is serialized. Variable v2


is not serialized because it is a static variable, and variable v3 is not serialized
because it is marked transient. If v3 were not marked transient, a
java.io.NotSerializableException would occur

4-24
Serialization
• Duplicate objects
– If an object is written to an object stream more than once, will it be stored in
multiple copies?
– No, it will not.
– When an object is written for the first time, a serial number is created for it. The
JVM writes the complete contents of the object along with the serial number
into the object stream. After the first time, only the serial number is stored if the
same object is written again. When the objects are read back, their references
are the same since only one object is actually created in the memory

4-25

You might also like