Java IO Stream
Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O system to
make input and output operation in java. In general, a stream means continuous flow of data.
Streams are clean way to deal with input/output without having every part of your code
understand the physical.
Java encapsulates Stream under java.io package. Java defines two types of streams. They are,
1. Byte Stream : It provides a convenient means for handling input and output of byte.
2. Character Stream : It provides a convenient means for handling input and output of
characters. Character stream uses Unicode and therefore can be internationalized.
Java Byte Stream Classes
Byte stream is defined by using two abstract class at the top of hierarchy, they are
InputStream and OutputStream.
These two abstract classes have several concrete classes that handle various devices such as
disk files, network connection etc.
Some important Byte stream classes.
Stream class Description
BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStream Used for Buffered Output Stream.
DataInputStream Contains method for reading java standard datatype
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
These classes define several key methods. Two most important are
1. read() : reads byte of data.
2. write() : Writes byte of data.
Java 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.
Some important Charcter stream classes
Stream class Description
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
We use the object of BufferedReader class to take inputs from the keyboard.
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.
// prg on reading a single character
import java.io.*;
class CharRead
public static void main( String args[])
throws Exception
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Any Character");
char c = (char)br.read(); //Reading character
System.out.println("The Given Char "+c);
Reading Strings in Java
To read string we have to use readLine() function with BufferedReader class's object.
Program to take String input from Keyboard in Java
// Prg on reading string with BufferedReader
import java.io.*;
class Testing
public static void main(String[] args) throws Exception
String st;
BufferedReader x = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter Any String");
st = x.readLine(); //Reading String
System.out.println("The Given String "+st);
Program to read from a file using BufferedReader class
import java. Io *;
class ReadTest
public static void main(String[] args)
try
File fl = new File("d:/myfile.txt");
BufferedReader br = new BufferedReader(new FileReader(fl)) ;
String str;
while ((str=br.readLine())!=null)
System.out.println(str);
br.close();
fl.close();
}
catch(IOException e) {
e.printStackTrace();
Program to write to a File using FileWriter class
// Prg on writing to file
import java.io.*;
class WriteTest
public static void main(String[] args)
try
File fl = new File("myfile.txt");
String str="All the best for the Supplementary and Regular Exams";
FileWriter fw = new FileWriter(fl) ;
fw.write(str);
fw.close();
System.out.println("File Successfully Created and Data was written into it");
catch (IOException e)
{
e.printStackTrace();
Java Serialization and Deserialization
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.
To implement serialization and deserialization, Java provides two classes ObjectOutputStream
and ObjectInputStream.
ObjectOutputStream class
It is used to write object states to the file. An object that implements java.io.Serializable
interface can be written to strams. It provides various methods to perform serialization.
ObjectInputStream class
An ObjectInputStream deserializes objects and primitive data written using an
ObjectOutputStream.
writeObject() and readObject() Methods
The writeObject() method of ObjectOutputStream class serializes an object and send it to the
output stream.
public final void writeObject(object x) throws IOException
The readObject() method of ObjectInputStream class references object out of stream and
deserialize it.
public final Object readObject() throws IOException,ClassNotFoundException
while serializing if you do not want any field to be part of object state then declare it
either static or transient based on your need and it will not be included during java serialization
process.
Example: Serializing an Object in Java
In this example, we have a class that implements Serializable interface to make its object
serialized.
import java.io.*;
class Studentinfo implements Serializable
String name;
int rid;
static String contact;
Studentinfo(String n, int r, String c)
this.name = n;
this.rid = r;
this.contact = c;
class Demo
public static void main(String[] args)
try
{
Studentinfo si = new Studentinfo("Abhi", 104, "110044");
FileOutputStream fos = new FileOutputStream("student.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(si);
oos.flush();
oos.close();
catch (Exception e)
System.out.println(e);
Object of Studentinfo class is serialized using writeObject() method and written
to student.txt file.
Example : Deserialization of Object in Java
To deserialize the object, we are using ObjectInputStream class that will read the object from
the specified file. See the below example.
import java.io.*;
class Studentinfo implements Serializable
String name;
int rid;
static String contact;
Studentinfo(String n, int r, String c)
this.name = n;
this.rid = r;
this.contact = c;
class Demo
public static void main(String[] args)
Studentinfo si=null ;
try
FileInputStream fis = new FileInputStream("/filepath/student.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
si = (Studentinfo)ois.readObject();
catch (Exception e)
e.printStackTrace(); }
System.out.println(si.name);
System.out. println(si.rid);
System.out.println(si.contact);
}
Output
Abhi
104
Null
transient Keyword
While serializing an object, if we don't want certain data member of the object to be serialized
we can mention it transient. transient keyword will prevent that data member from being
serialized.
class studentinfo implements Serializable
String name;
transient int rid;
static String contact;
Making a data member transient will prevent its serialization.
In this example rid will not be serialized because it is transient, and contact will also
remain unserialized because it is static.
RandomAccessFile
This class is used for reading and writing to random access file. A random access file behaves
like a large array of bytes. There is a cursor implied to the array called file pointer, by moving
the cursor we do the read write operations.
RandomAccessFile(File Creates a random access file stream to read from, and optionally to
file, String mode) write to, the file specified by the File argument.
Methods
Modifier Method Method
and Type
void close() It closes this random access file stream and releases
any system resources associated with the stream.
int readInt() It reads a signed 32-bit integer from this file.
void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.
void writeDouble(double It converts the double argument to a long using the
v) doubleToLongBits method in class Double, and then
writes that long value to the file as an eight-byte
quantity, high byte first.
void writeFloat(float v) It converts the float argument to an int using the
floatToIntBits method in class Float, and then writes
that int value to the file as a four-byte quantity, high
byte first.
void write(int b) It writes the specified byte to this file.
int read() It reads a byte of data from this file.
long length() It returns the length of this file.
void seek(long pos) It sets the file-pointer offset, measured from the
beginning of this file, at which the next read or write
occurs.
Example
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
static final String FILEPATH ="myFile.TXT";
public static void main(String[] args) {
try {
System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
writeToFile(FILEPATH, "I love my country and my people", 31);
} catch (IOException e) {
e.printStackTrace();
}
private static byte[] readFromFile(String filePath, int position, int size)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "r");
file.seek(position);
byte[] bytes = new byte[size];
file.read(bytes);
file.close();
return bytes;
private static void writeToFile(String filePath, String data, int position)
throws IOException {
RandomAccessFile file = new RandomAccessFile(filePath, "rw");
file.seek(position);
file.write(data.getBytes());
file.close();
The myFile.TXT contains text "This class is used for reading and writing to random access file."
after running the program it will contains
I love my country and my people.
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.*;
import javafx.scene.layout.*;
import javafx.scene.control.*;
public class Fx_Example2 extends Application
public void start(Stage primaryStage)
Label label1 = new Label("I love JavaFX!"); //show text
StackPane root = new StackPane(); //create a layout
root.getChildren().add(label1); //add the Label to the layout
Scene scene = new Scene(root,100,100);
primaryStage.setScene(scene); //set the Scene
primaryStage.show(); //show the Stage
public static void main(String[] args)
launch(args);