Open In App

How to Read and Write Binary Files in Java?

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The Binary files contain data in a format that is not human-readable. To make them suitable for storing complex data structures efficiently, in Java, we can read from the write to binary files using the Input and Output Streams.

In this article, we will learn and see the code implementation to read and write binary files in Java.

Syntax to Read from a Binary File:

InputStream inputStream = new FileInputStream("data.bin");
int data;
while ((data = inputStream.read()) != -1) {
// Process the read data
}
inputStream.close();

Syntax to Write to a Binary File:

OutputStream outputStream = new FileOutputStream("data.bin");
// Write data to the output stream
outputStream.close();

Program to Read and Write Binary Files in Java

Below is the implementation of Read and Write Binary Files in Java:

Java




// Java Program to Read and Write Binary Files
import java.io.*;
  
// Drver Class
public class GFG {
      // Main Function
    public static void main(String[] args) 
    {
        try {
              
              // Writing to binary file
            OutputStream Stream = new FileOutputStream("data.bin");
            Stream.write(new byte[]{0x48, 0x65, 0x6C, 0x6C, 0x6F}); 
              
              // ASCII values for "Hello"
            Stream.close();
              
              // Reading from a binary file
            InputStream inputStream = new FileInputStream("data.bin");
              
              int data;
            
            while ((data = inputStream.read()) != -1) {
                System.out.print((char) data); 
              // Convert byte to character
            }
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Output

Hello

Explanation of the above Program:

Writing to a Binary File:

  • We create an OutputStream object using the FileOutputStream and specify the file name.
  • We use the write() method to write binary data to output stream.

Reading from a Binary File:

  • We create an InputStream object using the FileInputStream and specify the file name.
  • We use the read() method to read binary data from input stream storing each byte in an integer variable.
  • We convert each byte to its corresponding ASCII character using the typecasting and print it to console.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads