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

Unit-7 File Handling (E-next.in)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit-7 File Handling (E-next.in)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Unit-7 File Handling

Q.1 Explain Object Serialization and deserialization with suitable example.


Q.2 What is serialization/desrialization of objects? Why do you need it? Give the example
with necessary code.
Q.3 What is object serialization? What is use of serialVersionUID?
Object Serialization and Deserialization in Java:
 Serialization is a process of converting an object into a sequence of bytes which can
be persisted to a disk or database or can be sent through streams. The reverse
process of creating object from sequence of bytes is called deserialization.
 A class must implement serializable interface present in java.io package in order to
serialize its object successfully.
 Serializable is a marker interface that adds serializable behaviour to the class
implementing it.

Object Serialization and Deserialization in Java

 Serialization in java is a mechanism of writing the state of an object into a byte


stream.
 It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.
 Java provides a mechanism, called object serialization where an object can be
represented as a sequence of bytes that includes the object's data as well as
information about the object's type and the types of data stored in the object.
 After a serialized object has been written into a file, it can be read from the file and
deserialized that is, the type information and bytes that represent the object and its
data can be used to recreate the object in memory.
 Most impressive is that the entire process is JVM independent, meaning an object
can be serialized on one platform and deserialized on an entirely different platform.
 Classes ObjectInputStream and ObjectOutputStream are high-level streams that
contain the methods for serializing and deserializing an object.
Java provide Serializable API encapsulated under java.io package for serializing and
deserializing object which include:
1. java.io.serializable
2. java.io.Externalizable
3. ObjectInputStream
4. ObjectOutputStream

Khan S. Alam 1 https://E-next.in


Unit-7 File Handling

Example of Java Serialization:


public class Employee implements java.io.Serializable
{
public String name;
public String address;
public transientint SSN;
public int number;

public void mailCheck()


{
System.out.println("Mailing a check to "+ name +" "+ address);
}
}

Notice that for a class to be serialized successfully, two conditions must be met:
 The class must implement the java.io.Serializable interface.
 All of the fields in the class must be serializable. If a field is not serializable, it must be
marked transient.
If you are curious to know if a Java Standard Class is serializable or not, check the
documentation for the class.
The test is simple: If the class implements java.io.Serializable, then it is serializable;
otherwise, it's not.

Advantage of Java Serialization:


 It is mainly used to travel object's state on the network (known as marshaling).
 java.io.Serializable interface:
 Serializable is a marker interface (has no data member and method). It is used to
"mark" java classes so that objects of these classes may get certain capability. The
Cloneable and Remote are also marker interfaces.
 It must be implemented by the class whose object you want to persist.
 The String class and all the wrapper classes implements java.io.Serializable interface
by default.

Let's see the example given below:


import java.io.Serializable;

public class Student implements Serializable


{
int id;
String name;

public Student(int id, String name)


{
this.id = id;
this.name = name;
}
}

Khan S. Alam 2 https://E-next.in


Unit-7 File Handling

In the above example, Student class implements Serializable interface. Now its objects can
be converted into stream.

ObjectOutputStream class:
 The ObjectOutputStream class is used to write primitive data types and Java objects
to an OutputStream.
 Only objects that support the java.io.Serializable interface can be written to streams.

Constructor
1) publicObjectOutputStream(OutputStream out) throws IOException {}: creates an
ObjectOutputStream that writes to the specified OutputStream.

Important Methods:
1) public final void writeObject(Object obj) throws IOException {}: writes the specified
object to the ObjectOutputStream.
2) public void flush() throws IOException {}: flushes the current output stream.
3) public void close() throws IOException {}: closes the current output stream.

Example of Java Serialization


 In this example, we are going to serialize the object of Student class.
 The writeObject() method of ObjectOutputStream class provides the functionality to
serialize the object.
 We are saving the state of the object in the file named f.txt.

import java.io.*;
class Persist
{
public static void main (String args []) throws Exception
{
Student s1 = new Student (211,"ravi");

FileOutputStream fout = new FileOutputStream ("f.txt");


ObjectOutputStream out = new ObjectOutputStream(fout);

out.writeObject(s1);
out.flush();

System.out.println("success");
}
}

Output:
Success

Khan S. Alam 3 https://E-next.in


Unit-7 File Handling

Deserialization In Java:
 Deserialization is the process of reconstructing the object from the serialized state.
 It is the reverse operation of serialization.

ObjectInputStream class
 An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.

Constructor
1) public ObjectInputStream(InputStream in) throws IOException {}: creates an
ObjectInputStream that reads from the specified InputStream.

Important Methods:
1) public final Object readObject() throws IOException, ClassNotFoundException{}:
reads an object from the input stream.
2) public void close() throws IOException {}: closesObjectInputStream.

Example of Java Deserialization

import java.io.*;

class Depersist
{

public static void main(String args[])throws Exception


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

Student s = (Student) in.readObject();


System.out.println (s.id+" "+s.name);

in.close();
}
}

Output:
211 ravi

Khan S. Alam 4 https://E-next.in


Unit-7 File Handling

Q.4 Which are the Stream classes? Explain It in detail.


Stream classes In Java:
 Java performs I/O through Streams. In general, a stream means continuous flow of
data.
 A stream can be defined as a sequence of data.
 In Java a stream is composed of bytes. It's called a stream because it is like a stream
of water that continues to flow.
 Java I/O (Input and Output) is used to process the input and produce the output.
 Java uses the concept of stream to make I/O operation fast.
 The java.io package contains all the classes required for input and output operations.
 We can perform file handling in java by Java I/O API.
In java, 3 streams are created for us automatically. All these streams are attached with
console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream

Java defines two types of streams. They are:


Byte Stream:
 It provides a convenient means for handling input and output of byte.
Character Stream:
 It provides a convenient means for handling input and output of characters.
Character stream uses Unicode and therefore can be internationalized.

Stream hierarchy diagram:

Khan S. Alam 5 https://E-next.in


Unit-7 File Handling

Byte Stream Classes:


 Byte stream is defined by using two abstract class at the top of hierarchy, they are
Input Stream and Output Stream.
 These two abstract classes have several concrete classes that handle various devices
such as disk files, network connection etc.

There are two kinds of Streams:


1. InPutStream:
 The InputStream is used to read data from a source.
 The InputStream class is the base class (superclass) of all input streams in the Java IO
API.
 InputStream Subclasses include the FileInputStream, BufferedInputStreamand the
PushbackInputStream among others.

FileInputStream example 1: read single character

import java.io.FileInputStream;
public class DataStreamExample
{
public static void main(String args[])
{
try
{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();

System.out.print((char)i);
fin.close();
}

catch(Exception e)
{
System.out.println(e);
}
}
}

Note: Before running the code, a text file named as "testout.txt" is required to be created.
In this file, we are having following content:
Welcome to MCA
After executing the above program, you will get a single character from the file which is 87
(in byte form). To see the text, you need to convert it into character.

Output:
W

Khan S. Alam 6 https://E-next.in


Unit-7 File Handling

Java FileInputStream example 2: read all characters

package com.MCA;
import java.io.FileInputStream;

public class DataStreamExample


{
public static void main(String args[])
{
try
{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;

while((i=fin.read())!=-1)
{
System.out.print((char)i);
}

fin.close();
}

catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
Welcome to MCA

2. OutPutStream:
 The OutputStream is used for writing data to a destination.
 The OutputStream class is the base class of all output streams in the Java IO API.
 Subclasses include the BufferedOutputStream and the FileOutputStream among
others.

Java FileOutputStream Example 1: write byte

import java.io.FileOutputStream;

public class FileOutputStreamExample


{
public static void main(String args[])
{

Khan S. Alam 7 https://E-next.in


Unit-7 File Handling

try
{

FileOutputStream fout = new FileOutputStream("D:\\testout.txt");


fout.write(65);
fout.close();

System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}

Output:
Success...
The content of a text file testout.txt is set with the data A.
testout.txt
A

Java FileOutputStream example 2: write string


import java.io.FileOutputStream;

public class FileOutputStreamExample


{
public static void main(String args[])
{
try
{

FileOutputStream fout=new FileOutputStream("D:\\testout.txt");


String s="Welcome to MCA.";

byte b[]=s.getBytes(); //converting string into byte array


fout.write(b);
fout.close();

System.out.println("success...");
}

catch(Exception e){System.out.println(e);}
}
}

Output:
Success...
The content of a text file testout.txt is set with the data Welcome to MCA.
testout.txt
Welcome to MCA.

Khan S. Alam 8 https://E-next.in


Unit-7 File Handling

Let's see the code to print output and error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");

These classes define several key methods. Two most important are
a) read(): reads byte of data.
b) write(): Writes byte of data.
c) flush(): flush byte of data.
d) close: close the file.

Some important Byte stream classes


BufferedInputStream: Used for Buffered Input Stream.
BufferedOutputStream: Used for Buffered Output Stream.
DataInputStream: Contains method for reading java standard data type
DataOutputStream: An output stream that contain method for writing java standard data
type
FileInputStream: Input stream that reads from a file
FileOutputStream: Output stream that write to a file.
InputStream: Abstract class that describe stream input.
OutputStream: Abstract class that describe stream output.
PrintStream: Output Stream that contain print() and println() method

Character Stream Classes


 Character stream is also defined by using two abstract class at the top of hierarchy,
they are Reader and Writer.
 These two abstract classes have several concrete classes that handle unicode
character.
 Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java
Character streams are used to perform input and output for 16-bit unicode.
 Though there are many classes related to character streams but the most frequently
used classes are, FileReader and FileWriter.
 Though internally FileReader uses FileInputStream and FileWriter uses
FileOutputStream but here the major difference is that FileReader reads two bytes at
a time and FileWriter writes two bytes at a time.

Example

import java.io.*;

public class CopyFile


{
public static void main(Stringargs[]) throwsIOException
{

FileReaderin = null;

Khan S. Alam 9 https://E-next.in


Unit-7 File Handling

FileWriterout = null;

try
{
in=newFileReader("input.txt");
out=newFileWriter("output.txt");

int c;
while((c =in.read())!=-1)
{
out.write(c);
}
}

finally
{
if(in!=null)
{
in.close();
}

if(out!=null)
{
out.close();
}
}
}
}

Some important Character stream classes.


BufferedReader: Handles buffered input stream.
BufferedWriter: Handles buffered output stream.
FileReader: Input stream that reads from file.
FileWriter: Output stream that writes to file.
InputStreamReader: Input stream that translate byte to character
OutputStreamReader: Output stream that translate character to byte.
PrintWriter: Output Stream that contain print() and println() method.
Reader: Abstract class that define character stream input
Writer: Abstract class that define character stream output

Reading Console Input Writer


 We use the object of BufferedReader class to take inputs from the keyboard.

Khan S. Alam 10 https://E-next.in


Unit-7 File Handling

Reading Characters
 read() method is used with BufferedReader object to read characters. As this
function returns integer type value has we need to use typecasting to convert it into
char type.

Below is a simple example explaining character input.


class CharRead
{

public static void main( String args[])


{
BufferedReader br = new Bufferedreader(new InputstreamReader(System.in));
char c = (char)br.read(); //Reading character
}
}

Reading Strings
 To read string we have to use readLine() function with BufferedReader class's object.
 Program to take String input from Keyboard in Java

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

InputStreamReader isr = new InputStreamReader(System.in);


BufferedReader br = new BufferedReader(isr);

text = br.readLine(); //Reading String


System.out.println(text);
}
}

Khan S. Alam 11 https://E-next.in


Unit-7 File Handling

Q.5 Differentiate between Byte Stream and Character Stream.

Byte Stream Character Stream


1) A byte stream access the file byte bye 1) A character stream read a file character
byte. by character.
2) Java Byte streams are used to perform 2) Java Character streams are used to
input and output of 8-bit bytes. perform input and output for 16-bit
unicode.
3) Byte stream is lower level concept than 3) Character Stream is higher level concept
Character Stream. than Byte Stream.
4) All byte stream classes are descended 4) All character stream classes are
from InputStream and OutputStream. descended from Reader and Writer.
5) Byte streams read bytes that fall under 5) Character streams read Unicode
ASCII range. characters that include characters of
many international languages.
6) Byte streams are intended for general 6) Character streams are intended
purpose input and output. exclusively for character data.

Q.6 Diffrence between Input stream and output stream.

Input Stream Output Stream


1) The InputStream is used to read data 1) The OutputStream is used for writing
from a source. data to a destination.
2) The InputStream class is the base class 2) The OutputStream class is the base class
(superclass) of all input streams in the of all output streams in the Java IO API.
Java IO API.
3) InputStream Subclasses include the 3) Output Stream Subclasses include the
FileInputStream, BufferedOutputStream and the
BufferedInputStreamand the FileOutputStream among others.
PushbackInputStream among others.
4) FileInputStream creates an InputStream 4) FileOutputStream creates an
that you can use to read bytes from a OutputStream that you can use to writes
file. bytes to a file.
5) ByteArrayInputStream creates an 5) ByteArrayOutputStream creates a
InputStream from array of bytes. It uses OutputStream that you can use to write
inmemory byte array to create bytes to in memory data structure.
ByteArrayInputStream.

Khan S. Alam 12 https://E-next.in


Unit-7 File Handling

Q.7 What is Buffered Reader/Writer.


Buffered Reader:
 Java BufferedReader class is used to read the text from a character-based input
stream.
 It can be used to read data line by line by readLine() method. It makes the
performance fast. It inherits Reader class.
 The Java.io.BufferedReader class reads text from a character-input stream, buffering
characters so as to provide for the efficient reading of characters, arrays, and lines.

Following are the important points about BufferedReader:


 The buffer size may be specified, or the default size may be used.
 Each read request made of a Reader causes a corresponding read request to be
made of the underlying character or byte stream.

Field
Following are the fields for Java.io.BufferedReader class:
protected Object lock: This is the object used to synchronize operations on this stream.

Methods inherited
This class inherits methods from the following classes:
1. Java.io.Reader
2. Java.io.Object

Java BufferedReader class declaration


Let's see the declaration for Java.io.BufferedReader class:
1) public class BufferedReader extends Reader

Java BufferedReader Example


 In this example, we are reading the data from the text file testout.txt using Java
BufferedReader class.

package com.MCA;
import java.io.*;

public class BufferedReaderExample


{
public static void main(String args[]) throws Exception
{

FileReader fr=new FileReader("D:\\testout.txt");


BufferedReader br=new BufferedReader(fr);

int i;
while((i=br.read())!=-1)
{
System.out.print((char)i);

Khan S. Alam 13 https://E-next.in


Unit-7 File Handling

br.close();
fr.close();
}
}
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to MCA.

Output:
Welcome to MCA.

Reading data from console by InputStreamReader and BufferedReader:


 In this example, we are connecting the BufferedReader stream with the
InputStreamReader stream for reading the line by line data from the keyboard

package com.MCA;
import java.io.*;

public class BufferedReaderExample


{
public static void main(String args[]) throws Exception
{

InputStreamReader r=new InputStreamReader(System.in);


BufferedReader br=new BufferedReader(r);

System.out.println("Enter your name");


String name=br.readLine();
System.out.println("Welcome "+name);
}
}

Output:
Enter your name
Nakul Jain
Welcome Nakul Jain

Java Buffered Writer:


 Java BufferedWriter class is used to provide buffering for Writer instances.
 It makes the performance fast. It inherits Writer class.
 The buffering characters are used for providing the efficient writing of single arrays,
characters, and strings.
 The Java.io.BufferedWriter class writes text to a character-output stream, buffering
characters so as to provide for the efficient writing of single characters, arrays, and
strings.

Khan S. Alam 14 https://E-next.in


Unit-7 File Handling

Following are the important points about BufferedWriter:


 The buffer size may be specified, or the default size may be used.
 A Writer sends its output immediately to the underlying character or byte stream.

Field
Following are the fields for Java.io.BufferedWriter class:
protected Object lock: This is the object used to synchronize operations on this stream.

Methods inherited
This class inherits methods from the following classes:
1. Java.io.Writer
2. Java.io.Object

Class declaration
Let's see the declaration for Java.io.BufferedWriter class:
1. public class BufferedWriter extends Writer

Example of Java BufferedWriter


 Let's see the simple example of writing the data to a text file testout.txt using Java
BufferedWriter.

package com.MCA;
import java.io.*;

public class BufferedWriterExample


{
public static void main(String[] args) throws Exception
{

FileWriter writer = new FileWriter("D:\\testout.txt");


BufferedWriter buffer = new BufferedWriter(writer);

buffer.write("Welcome to MCA.");
buffer.close();

System.out.println("Success");
}
}

Output:
success

testout.txt:
Welcome to MCA.

Khan S. Alam 15 https://E-next.in

You might also like