Unit-7 File Handling (E-next.in)
Unit-7 File Handling (E-next.in)
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.
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.
import java.io.*;
class Persist
{
public static void main (String args []) throws Exception
{
Student s1 = new Student (211,"ravi");
out.writeObject(s1);
out.flush();
System.out.println("success");
}
}
Output:
Success
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.
import java.io.*;
class Depersist
{
in.close();
}
}
Output:
211 ravi
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
package com.MCA;
import java.io.FileInputStream;
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.
import java.io.FileOutputStream;
try
{
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
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.
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.
Example
import java.io.*;
FileReaderin = null;
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();
}
}
}
}
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.
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;
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
package com.MCA;
import java.io.*;
int i;
while((i=br.read())!=-1)
{
System.out.print((char)i);
br.close();
fr.close();
}
}
Here, we are assuming that you have following data in "testout.txt" file:
Welcome to MCA.
Output:
Welcome to MCA.
package com.MCA;
import java.io.*;
Output:
Enter your name
Nakul Jain
Welcome Nakul Jain
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
package com.MCA;
import java.io.*;
buffer.write("Welcome to MCA.");
buffer.close();
System.out.println("Success");
}
}
Output:
success
testout.txt:
Welcome to MCA.