File I/O Introduction
The following is the list methods
going to cover in File I/O Concept.
1) File
2 )FileWriter
3) FileReader
4) BufferedWriter
5 )BufferedReader
6) printWriter
File A java file object represent just
name of the file/directory.
File f = new
File(“abc.txt”);
If ‘abc.txt’ is already available
then ‘f’ will represent that physical file. If it is not already available, It
won’t create any new file and ‘f’ simply represents the name of the file.
Ex:
import java.io.*;
class test
{
public static void main(String[] args)
{
File f = new File("cba.txt");
System.out.println(f.exists()); à false at first time.
f.createNewFile();
System.out.println(f.exists()); à true
}
}
I Run:
false
true
II Run:
true
true
A java file Object can represent
directories also
Ex:
File f =
new File("bbc");
System.out.println(f.exists());
f.mkdir();
System.out.println(f.exists());
I Run:
false
true
II Run:
true
true
The constructors of the file class
1) File f = new File(String name)
Here name
may be file or directory name.
Creates a java file object that
represents a file or directory name.
2) File f = new File(String
subdirec, String name)
Creates a java file object that
represents file or directory name present in specified
subdirectory.
3) File f = new File(File subdir,
String name)
Important methods of File Class
1) boolean exists(): returns true if
the physical file/directory presents other wise false.
2) boolean createNewFile(): returns
ture if it creates a new file, if the required file is already available then it
won’t create any new file and returns false.
3) booelan mkdir() For creation of
directory.
4) boolean isFile(): returns true if
the java file object represents a file.
5) boolean isDirectory(): returns
true if the java file object represents a directory.
6) String à
list(): returns the names of files and directories present in the directories
represented by the file object. If the java file object represents a file
instead of directory this method returns null.
7) Boolean delete(): for deleting
the file or directory represented by java file object.
write a program to create a file
named with ‘xyz.txt’ in the current working directory.
File f =
new File(“xyz.txt”);
f.createNewFile();
Write a program to create a
directory ‘raju123’ in the current working directory and create a file
‘file1.txt’ in that directory.
File f =
new File(“raju123”);
f.mkdir();
// File
f1 = new File(“raju123”,”file1.txt”);
File f1 =
new File(f,”file1.txt”);
F1.createNewFile();
Write a program to list the names of
files and directories in ‘jdk’ directory.
File f =
new File(“jdk”);
String []
s = f.list();
For(String
s1: s)
{
System.out.println(s1);
}
FileWriter
This
class can be used for writing character data to the file.
Constructors
1)
FileWriter fw = new FileWriter(String fname)
2)
FileWriter fw = new FileWriter(File f);
The above 2 constructors creates a
file object to write character data to the file.
If the file already contains some data
it will overwrite with the new data. Instead of overriding if u have to perform
append then we have to use the following constructors.
FileWriter fw = new
FileWriter(String name, boolean append);
FileWriter fw = new FileWriter(File
f, boolean append);
If the underlying physical file is
not already available then the above constructors will create the required file
also.
Important methods of FileWriter
Class
1) void write(int ch) throws
IOException for writing single character to the file.
2) void write(String s)throws
IOException.
3) void write(char [] ch) throws
IOException.
4) void flush():-To guaranteed that
the last character of the data should be required to the file.
Ex:-
class test
{
public
static void main(String arg[])throws Exception
{
File
f = new File("pongal.txt");
System.out.println(f.exists());
FileWriter
fw = new FileWriter(f,true);
System.out.println(f.exists());
fw.write(97);
fw.write("run\nsoftware\n");
char
[] ch1 = {'a','b','c'};
fw.write(ch1);
fw.flush();
fw.close();
}
}
FileReader This class can be used for reading
character data from the file.
Constructors
1)
FileReader fr = new FileReader(String name);
2)
FileReader fr = new FileReader(File f);
Important methods of FileReader
Class
1) int read(): for reading next
character from the file. If there is no next character this method returns -1
2) int read(char[] ch): to read data
from the file into char array.
3) void close(): to close FileReader
Ex:
class test
{
public
static void main(String arg[])throws Exception
{
File
f = new File("pongal.txt");
FileReader
fr = new FileReader(f);
System.out.println(fr.read());
char
[] ch2 = new char[(int) (f.length())];
System.out.println(ch2.length);
fr.read(ch2);
for(char
ch1: ch2)
{
System.out.print(ch1);
}
}
}
The usage of FileReader and
FileWriter is in efficient because
While writing the data
by using FileWriter, program is responsible to insert line separators manually.
We can read the data
character by character only by using FileReader. If increases the number of I/O
operations and effect performance.
To overcome these problems sun
people has introduced BufferedReader and BufferedWriter classes.
BufferedWriter This can be used for writing
character data to the file.
Constructors
1) BufferedWriter bw = new
BufferedWriter(writer w)
2) BufferedWriter bw = new BufferedWriter(writer
r, int size)
BufferedWriter never communicates
directly with the file. It should Communicate through some writer object only.
Q) Which of the following are valid
declarations
1) BufferedWriter bw = new
BufferedWriter(“abc.txt”); X
2) BufferedWriter bw = new
BufferedWriter(new File(“abc.txt”)); X
3) BufferedWriter bw = new
BufferedWriter(new FileWriter(“abc.txt”));
4) BufferedWriter bw = new
BufferedWriter(new BufferedWriter(new
FileWriter(“abc.txt”)));
5)
Important methods of BufferedWriter
Class
1) void write(int ch) thorows
IOException
2) void write(String s) throws
IOException
3) void write(char[] ch) throws
IOException
4) void newLine()
for inserting a new line character.
5) void flush()
6) void close()
7)
Which method is available in
BufferedWriter and not available in FileWriter
Ans: newLine() method
Ex:-
class test
{
public
static void main(String arg[])throws Exception
{
File
f = new File("pongal.txt");
System.out.println(f.exists());
FileWriter
fw = new FileWriter(f);
BufferedWriter
bw = new BufferedWriter(fw);
bw.write(97);
bw.newLine();
char
[] ch1 = {'a','b','c','d'};
bw.write(ch1);
bw.newLine();
bw.write("raju");
bw.newLine();
bw.write("software");
bw.flush();
bw.close();
}
}
Note:- When ever we r closing
BufferedWriter ,automatically underlying FileWriter object will be closed.
BufferedReader By using this class we can read
character data from the file.
Constructors
1) BufferedReader br = new
BufferedReader(Reader r)
2) BufferedReader br = new
BufferedReader(Reader r, int buffersize)
BufferedReader never communicates
directly with the file. It should Communicate through some reader object only.
Important methods of BufferedReader
Class
BufferedWriter
FileWriter
1) int read()
2) int read(char [] ch)
3) String readLine();
Reads the next line present in the
file. If there is no nextline this method returns null.
4) void close()
Ex:
class test
{
public
static void main(String arg[])throws Exception
{
FileReader
fr = new FileReader("pongal.txt");
BufferedReader
br = new BufferedReader(fr);
String
s = br.readLine();
while(s
!= null)
{
System.out.println(s);
s =
br.readLine();
}
br.close();
}
}
Note:- When ever we r closing
BufferedReader ,automatically underlying FileReader object will be closed.
PrintWriter
The most enhanced writer for writing
character data to the file is PrintWriter()
Constructors
1) PrintWriter pw = new
PrintWriter(String fname)
2) PrintWriter pw = new
PrintWriter(File f);
3) PrintWriter pw = new
PrintWriter(Writer w);
Important methods
1) write(int ch)
2) write(char [] ch)
3) write(String s)
4) print(int i)
print(double d)
print(char ch)
print(Boolean b)
print(char ch[])
5) void flush()
6) close()
Ex:
class test
{
public
static void main(String arg[])throws Exception
{
FileWriter
fw = new FileWriter("pongal.txt");
PrintWriter
out = new PrintWriter(fw);
out.write(97);
out.println(100);
out.println(true);
out.println('c');
out.println("FDGH");
out.flush();
out.close();
}
}
Serialization Introduction
Serialization: The Process of Saving an object to a
file is called “serialization”. But strictly speaking serialization is the
process of converting an object from java supported format to network
or file supported format. By using FileOutPutStream,
ObjectOutPutStream classes we can achieve serialization
Deserialization: The process of reading an object
from a file is called deserialization. But strictly speaking it is the process
of Converting an object from network supported format or file supported
format to java supported format.
By using FileInputStream, ObjectInputStream
we can achieve deserialization.
Ex:-
class Dog implements Serializable
{
int i=
10;
int j=
20;
}
class serializedemo
{
public
static void main(String arg[])
{
Dog
d = new Dog();
FileOutputStream
fos = new FileOutputStream("abc.ser");
ObjectOutputStream
oos = new ObjectOutputStream(fos);
oos.writeObject(d);
FileInputStream
fis = new FileInputStream("abc.ser");
ObjectInputStream
ois = new ObjectInputStream(fis);
Dog
d1 = (Dog)ois.readObject();
System.out.println(d1.i+"---"+d2.j);
Dog
}
}
We can perform serialization only
for serialization objects. An Object is said to be serializable if and only if
the corresponding class should implement serializable
interface. serializable interface
present in java.io package and doesn’t contain any method, it is marker interface.
If u r trying to perform serialization of a non serialization Object. we will
get runtime exception saying NonSerializableException.
If we don’t want to Serialize the
value of a particular variable (To meet security constraints) we should declare
those variables as transient. While performing serialization JVM ignores the
value of transient variables and saves default values instead of
original values. static variables are not part of object state and hence
they won’t participate in serialization process Declaring static variables as
transient there is no impact similarly declaring final variables as transient creates
no impact.
Declaration
|
O/P
|
int i = 10;
int j = 20;
|
10…20
|
staic int i = 10;
staic transient int j = 20;
|
10…20
|
transient int i = 10;
staic transient int j = 20;
|
0…20
|
transient static int i = 10;
transient int j = 20;
|
10…0
|
transient int i = 10;
transient final int j = 20;
|
0…20
|
Serialization in the case of Object
Graphs
When ever we are saving an object to
a file all the objects which are reachable from that object will be saved by
default. This group of objects is called ‘Object Graph’.
In the Object Graph if any Object is
non-Serialzable we will get runtime Exception saying not- serializable Exception.
Ex:-
import java.io.*;
class Dog implements Serializable
{
Cat c =
new Cat();
}
class Cat implements Serializable
{
Rat r =
new Rat();
}
class Rat implements Serializable
{
int j=
20;
}
class SerializeDemo
{
public
static void main(String arg[])throws Exception
{
Dog
d = new Dog();
FileOutputStream
fos = new FileOutputStream("abc.ser");
ObjectOutputStream
oos = new ObjectOutputStream(fos);
oos.writeObject(d);
FileInputStream
fis = new FileInputStream("abc.ser");
ObjectInputStream
ois = new ObjectInputStream(fis);
Dog
d1 = (Dog)ois.readObject();
System.out.println(d1.c.r.j);
}
}
O/P:- 20
In the above program among Dog, Cat
and Rat classes if any class is not Serializable we will get runtime Exception
saying java.io.NotSerializableException.
Customized Serialization
During default Serialization there
may be a chance of loss of information because of transient variables.
Ex:-
import java.io.*;
class Dog implements Serializable
{
transient
Cat c = new Cat();
}
class Cat
{
int j=
20;
}
class SerializeDemo
{
public
static void main(String arg[])throws Exception
{
Dog
d = new Dog();
System.out.println("Before
Serialization:"+d.c.j);
FileOutputStream
fos = new FileOutputStream("abc.ser");
ObjectOutputStream
oos = new ObjectOutputStream(fos);
oos.writeObject(d);
FileInputStream
fis = new FileInputStream("abc.ser");
ObjectInputStream
ois = new ObjectInputStream(fis);
Dog
d1 = (Dog)ois.readObject();
System.out.println(d1.c.j);
}
}
Inheritance in Serialization
If the parent class is Serializable
bydefault all the child classes also Serializable. i.e Serializable nature is inherited
from parent to child.
Ex:-
import java.io.*;
class Animal implements Serializable
{
int i =
10;
}
class Dog extends Animal
{
int j =
20;
}
class SerializeDemo
{
public
static void main(String arg[])throws Exception
{
Dog
d = new Dog();
FileOutputStream
fos = new FileOutputStream("abc.ser");
ObjectOutputStream
oos = new ObjectOutputStream(fos);
oos.writeObject(d);
FileInputStream
fis = new FileInputStream("abc.ser");
ObjectInputStream
ois = new ObjectInputStream(fis);
Dog
d1 = (Dog)ois.readObject();
System.out.println(d1.i+"-----"+d1.j);
}
}
If the child class is Serializable
and some of the parent classes are not Serializable, Still we are allowed to serialize
child class Objects. While performing serialization JVM ignores the inherited
variables which are coming from non-serializable parents.
While performing de-serialization
JVM will check is there any parent class is non-serializable or not. If any
parent is non-serializable JVM will create an object for every non-serializable
parent and share it’s instance variables for the current child object. The
non-serializable parent class should compulsory contain no-argument
constructor other wise we will get runtime error.
Ex:-
import java.io.*;
class Animal
{
int i =
10;
Animal()
{
System.out.println("Animal
Constructor");
}
}
class Dog extends Animal implements
Serializable
{
int j =
20;
Dog()
{
System.out.println("Dog
Constructor");
}
}
class SerializeDemo
{
public
static void main(String arg[])throws Exception
{
Dog
d = new Dog();
d.i
= 888;
d.j
= 999;
System.out.println(d.i+"-----"+d.j);
System.out.println("Serilization
Started");
FileOutputStream
fos = new FileOutputStream("abc.ser");
ObjectOutputStream
oos = new ObjectOutputStream(fos);
oos.writeObject(d);
System.out.println("Deserialization
Started");
FileInputStream
fis = new FileInputStream("abc.ser");
ObjectInputStream
ois = new ObjectInputStream(fis);
Dog
d1 = (Dog)ois.readObject();
System.out.println(d1.i+"-----"+d1.j);
}
}
No comments:
Post a Comment