Download Our Beta Android App And Help Us Build Awesome Stuff!  Download Now.

Java Program Read and Write to a Binary File example

binary.txt
File size: 1.46 KB

File content type: text/plain

Category: Practical Files and Assignment

Course: B.Tech., ISC Board, and ICSE Board

Semester: 5

College: Guru Gobind Singh Indraprastha University(GGSIPU)


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();

    }

}

Added by passhojao

Comments