Our Android App Also Got an Upgrade. Download now!

Java Program Read and Write to a Binary File example

read_write_binary_file.txt

File size: 1.46 KB

File content type: text/plain

Category: Practical Files

Subject: Java Programming

import java.io.*;

public class BinaryFileExample {

    public static void main(String[] args) throws Exception {

        // file extension can be anything doesn't matter
        FileOutputStream fileOutputStream = new FileOutputStream("test.obj");
        DataOutputStream out = new DataOutputStream(fileOutputStream);

        // generally custom objects are stored in binary format like image, video, game data etc
        // decide how data need to be stored in binary file

        // we will store a list of 3 student info, Name and then Roll Number

        out.writeUTF("Hamid");
        out.writeInt(1);

        out.writeUTF("Rohan");
        out.writeInt(2);

        out.writeUTF("Shubham");
        out.writeInt(3);

        out.close(); // close the stream


        // Now reading from same file we created, We should know the format in which the binary file was created
        // first is name then is roll number, if we try first roll number then name we get error

        FileInputStream fileInputStream = new FileInputStream("test.obj");
        DataInputStream in = new DataInputStream(fileInputStream);


        try {
            while (true) {
                String name = in.readUTF();
                int rollNumber = in.readInt();
                System.out.println("Name = " + name + " Roll Number  = " + rollNumber);
            }
        } catch (EOFException e) {
            System.out.println("Finished reading file");
        }

        in.close();

    }

}

Read Binary File in Java
Write Binary File in Java Example

Last Updated: July 16, 2022