Java IO
Java IO
Java IO
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.
Stream
A stream is 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..2K
A byte stream access the file byte by byte. A byte stream is suitable for any kind of file, however
not quite appropriate for text files. For example, if the file is using a unicode encoding and a
character is represented with two bytes, the byte stream will treat these separately and you will
need to do the conversion yourself.
A character stream will read a file character by character. A character stream needs to be given
the file's encoding in order to work properly.
mer for the Riot Balance Team - Best of LoL Streams #371
In Java, 3 streams are created for us automatically. All these streams are attached with
the console.
Let's see the code to print output and an error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");
OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given below:
OutputStream
Java application uses an output stream to write data to a destination; it may be a file,
an array, peripheral device or socket.
InputStream
Java application uses an input stream to read data from a source; it may be a file, an
array, peripheral device or socket.
Let's understand the working of Java OutputStream and InputStream by the figure
given below.
OutputStream class
OutputStream class is an abstract class. It is the superclass of all classes representing
an output stream of bytes. An output stream accepts output bytes and sends them to
some sink.
Method Description
1) public void write(int)throws IOException is used to write a byte to the current output stream.
OutputStream Hierarchy
InputStream class
InputStream class is an abstract class. It is the superclass of all classes representing an
input stream of bytes.
Method Description
1) public abstract int read()throws reads the next byte of data from the input stream. It returns
IOException the end of the file.
2) public int available()throws returns an estimate of the number of bytes that can be read
IOException the current input stream.
InputStream Hierarchy
Java FileOutputStream Class
Java FileOutputStream is an output stream used for writing data to a file.
If you have to write primitive values into a file, use FileOutputStream class. You can
write byte-oriented as well as character-oriented data through FileOutputStream class.
But, for character-oriented data, it is preferred to use FileWriter than
FileOutputStream.
Example
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Java FileInputStream Class
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-
oriented data (streams of raw bytes) such as image data, audio, video etc. You can also
read character-stream data. But, for reading streams of characters, it is recommended
to use FileReader class.
Ex:
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);}
}
}
For serializing the object, we call the writeObject() method ObjectOutputStream, and
for deserialization we call the readObject() method of ObjectInputStream class.
We must have to implement the Serializable interface for serializing the object.
java.io.Serializable interface
Serializable is a marker interface (has no data member and method). It is used to
"mark" Java classes so that the objects of these classes may get a certain capability.
The Cloneable and Remote are also marker interfaces.
The String class and all the wrapper classes implement the java.io.Serializable interface
by default.
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 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.
ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.
import java.io.*;
class Persist{
public static void main(String args[]){
try{
//Creating the object
Student s1 =new Student(211,"ravi");
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("f.txt");
ObjectOutputStream out=new ObjectOutputStream(fout);
out.writeObject(s1);
out.flush();
//closing the stream
out.close();
System.out.println("success");
}catch(Exception e){System.out.println(e);}
}
}
success
Example of Java Deserialization
Deserialization is the process of reconstructing the object from the serialized state. It
is the reverse operation of serialization. Let's see an example where we are reading the
data from a deserialized object.
import java.io.*;
class Depersist{
public static void main(String args[]){
try{
//Creating stream to read the object
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
Student s=(Student)in.readObject();
//printing the data of the serialized object
System.out.println(s.id+" "+s.name);
//closing the stream
in.close();
}catch(Exception e){System.out.println(e);}
}
}
211 ravi