Files and I/O
Files and I/O
InputStream: Java application uses an input stream to read data from a source,
it may be a file,an array,peripheral device or socket.
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes(Binary
Data)
Character Streams
Java Character streams are used to perform input and output for 16-bit
unicode.
Byte Stream Hierarchy
int i=0;
while((i=bin.read())!=-1){
bout.write(i);
}
bin.close();
bout.close();
}
}
Serialization :
java.io.Serializable interface
Example:
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;
}
}
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 persistence");
} }
Example of Java Deserialization
import java.io.*;
class Depersist{
public static void main(String args[])throws Exception{
in.close();
}
}