Binary File Handling in Java
File Handling in Java
In this lesson, we will learn how to handle binary file in Java.
What is Binary File Handling
Binary File Handling is a process in which we create a file and store data in its original format. It means that if we stored an integer value in a binary file, the value will be treated as an integer rather than text.
Binary files are mainly used for storing records just as we store records in a database. It makes it easier to access or modify the records easily.
We will use the following classes given below to handle data in a binary file.
- FileOutputStream : used for writing streams of raw bytes to a binary file
- DataOutputStream : used for writing primitive data types to an output stream.
- FileInputStream : used for reading streams of raw bytes from a binary file.
- DataInputStream : used for reading primitive data types from an input stream.
A stream in Java means follow of bytes from one source to another.
Write primitive data types to a binary file
The program below demonstrates how to write primitive data types in a binary file using the FileOutputStream and DataOutputStream classes.
Example
import java.io.*;
public class Example
{
public static void main(String args[])
{
boolean bo = true;
byte byt = 12;
char ch = 'A';
short sh = 256;
int it = 5862;
long lg = 458671;
float ft = 78.214f;
double db = 2458.325;
String str = "Hello Java";
// create a File object
File f=new File("d:/delta.txt");
// declare a FileOutputStream object
FileOutputStream fos=null;
// declare a DataOutputStream object
DataOutputStream dos=null;
try
{
// initialize the FileOutputStream object by passing the File object
fos=new FileOutputStream(f);
// initialize the DataOutputStream object by passing the FileOutputStream object
dos=new DataOutputStream(fos);
// write primitive data types to a binary file using
// the various method of DataOutputStream class
dos.writeBoolean(bo);
dos.writeByte(byt);
dos.writeChar(ch);
dos.writeShort(sh);
dos.writeInt(it);
dos.writeLong(lg);
dos.writeFloat(ft);
dos.writeDouble(db);
// to write string use writeUTF(string) method of DataOutputStream
dos.writeUTF(str);
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
// close the file
fos.close();
dos.close();
}
catch(IOException e) {}
}
}
}
Read primitive data types from a binary file
The program below demonstrates how we can read primitive data types from a binary file using the FileInputStream and DataInputStream classes. We have to read data in the same order we have written it in the file.
Example
import java.io.*;
public class Example
{
public static void main(String args[])
{
boolean bo;
byte byt;
char ch;
short sh;
int it;
long lg;
float ft;
double db;
String str;
// create a File object
File f=new File("d:/delta.txt");
// declare a FileInputStream object
FileInputStream fis=null;
// declare a DataInputStream object
DataInputStream dis=null;
try
{
// initialize the FileInputStream object by passing the File object
fis=new FileInputStream(f);
// initialize the DataInputStream object by passing the FileInputStream object
dis=new DataInputStream(fis);
// read primitive data types from a binary file using
// the various method of DataInputStream class
bo=dis.readBoolean();
byt=dis.readByte();
ch=dis.readChar();
sh=dis.readShort();
it=dis.readInt();
lg=dis.readLong();
ft=dis.readFloat();
db=dis.readDouble();
// to read string use readUTF(string) method of DataOutputStream
str=dis.readUTF();
System.out.println("Boolean data = " + bo);
System.out.println("Byte data = " + byt);
System.out.println("Char data = " + ch);
System.out.println("Short value = " + sh);
System.out.println("Int data = " + it);
System.out.println("Long data = " + lg);
System.out.println("Float data = " + ft);
System.out.println("Double data = " + db);
System.out.println("String data = " + str);
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
// close the file
fis.close();
dis.close();
}
catch(IOException e) {}
}
}
}
Output
Boolean data = true Byte data = 12 Char data = A Short value = 256 Int data = 5862 Long data = 458671 Float data = 78.214 Double data = 2458.325 String data = Hello Java
Write an object to a binary file
By implementing the Serializable interface to the user-defined class, we can write an object of the user-defined class in a binary file using the FileOutputStream and ObjectOutputStream classes.
Example
import java.io.*;
import java.util.Scanner;
class Student implements Serializable
{
public int roll;
public String name;
Student()
{
roll=0;
name="None";
}
Student(int r, String n)
{
roll=r;
name=n;
}
}
public class Example
{
public static void main(String args[])
{
// create a File object
File f=new File("d:/delta.txt");
// declare a FileOutputStream object
FileOutputStream fos=null;
// declare a ObjectOutputStream object
ObjectOutputStream oos=null;
// create a Scanner class object
Scanner sc=new Scanner(System.in);
// create a Student class object
Student s=new Student();
// store the student information in the object s
System.out.print("Roll: ");
s.roll=sc.nextInt();
sc.nextLine();
System.out.print("Name: ");
s.name=sc.nextLine();
try
{
// initialize the FileOutputStream object by passing the File object
fos=new FileOutputStream(f);
// initialize the ObjectOutputStream object by passing the FileOutputStream object
oos=new ObjectOutputStream(fos);
// write object to the file
oos.writeObject(s);
System.out.println("Object written to the file");
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
// close the file
fos.close();
oos.close();
}
catch(IOException e) {}
}
}
}
Output
Roll: 1 Name: Thomas Object written to the file
Read an object from a binary file
We can read an object of a user-defined class from a binary file using the FileInputStream and ObjectInputStream classes.
Example
import java.io.*;
class Student implements Serializable
{
public int roll;
public String name;
Student()
{
roll=0;
name="None";
}
Student(int r, String n)
{
roll=r;
name=n;
}
}
public class Example
{
public static void main(String args[])
{
// create a File object
File f=new File("d:/delta.txt");
// declare a FileInputStream object
FileInputStream fis=null;
// declare a ObjectInputStream object
ObjectInputStream ois=null;
// create a Student class object
Student s=new Student();
try
{
// initialize the FileOutputStream object by passing the File object
fis=new FileInputStream(f);
// initialize the ObjectInputStream object by passing the FileInputStream object
ois=new ObjectInputStream(fis);
// read object from the file an typecast it by the Student class
s=(Student)ois.readObject();
System.out.println("Roll: "+s.roll);
System.out.println("Name: "+s.name);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
try
{
// close the file
fis.close();
ois.close();
}
catch(IOException e) {}
}
}
}
Output
Roll: 1 Name: Thomas