How to Read and Write Binary Files in Java?
Last Updated :
14 Feb, 2024
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
import java.io.*;
public class GFG {
public static void main(String[] args)
{
try {
OutputStream Stream = new FileOutputStream( "data.bin" );
Stream.write( new byte []{ 0x48 , 0x65 , 0x6C , 0x6C , 0x6F });
Stream.close();
InputStream inputStream = new FileInputStream( "data.bin" );
int data;
while ((data = inputStream.read()) != - 1 ) {
System.out.print(( char ) data);
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
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.
Share your thoughts in the comments
Please Login to comment...