How to Read and Write Binary Files in Java?

How to Read and Write Binary Files in Java?

Binary files play a pivotal role in Java for handling non-textual data efficiently. Learning to “Read and Write binary files in Java” using FileInputStream and FileOutputStream, coupled with BufferedInputStream and BufferedOutputStream, equips developers with essential tools to work with diverse data types. Binary File is a computer-readable, non-human readable file that consists of raw data represented as a sequences of 0โ€™s and 1โ€™s.

Unlike Text File that contains characters/text which are encoded using specific encoding method such
as (UTF-8, ASCII), binary File stores data in binary format. Binary File. This make binary file more
suitable for storing data of varied types like images, videos, audio, multimedia, executable (.exe) and
serialized objects.ย 

What Is The Purpose of Binary Files in Java?

In Java, binary files are used for various purposes, including:
1. Multimedia: Images, Videos, audio clips are stored as binary data in a file. This maintains data
integrity and reduces storage.
2. Serialized objects: Java objects are serialized and stored in binary format. Serialization is
useful when transferring java objects to different applications.
3. .class file: When Java program is compiled, a .class file is created. This files are binary files that
contains machine understandable bytecode.

Let’s Explore Various Approaches for Reading and Writing Binary Files.

Approach 1: Using FileInputStream and FileOutputStream.

FileInputStream and FileOutputStream classes are straightforward way for reading from and writing
to binary files.

Writing using `FileOutputStream`

To write binary data, we create a `FileOutputStream` named “outputStream” pointing to the file
“SampleFile.bin”. We prepare a string `msg` with the content “Hello, Hope You are Learning Java”.
Using getBytes(), we convert the string data into bytes, which are then written to the `outputStream`.
It’s crucial to close the `outputStream` instance to prevent data leakage.

Reading using `FileInputStream`

For Reading File, A byte array buffer is used to read data from the file in chunks. The
inputStream.read(buffer) method reads data into the buffer, returning the number of bytes read or –
1 if the end of the file is reached.
The data is then converted back to characters using (char) buffer[i]) and printed until the end of the
file.

Java code showing read and write example
				
					import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ReadWriteIO {
public static void main(String[] args) {
// Write binary data to a file
try (FileOutputStream outputStream = new FileOutputStream("SampleFile.bin")) {
String msg = "Hello, Hope you having fun time learning Java";
outputStream.write(msg.getBytes());
outputStream.close();
} catch (IOException e) {
System.err.println("Error writing binary file: " + e.getMessage());
}
// Read binary data from a file
try (FileInputStream inputStream = new FileInputStream("SampleFile.bin")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
for (int i = 0; i < bytesRead; i++) {
System.out.print((char) (buffer[i]));
}
}
inputStream.close();
} catch (IOException e) {
System.err.println("Error reading binary file: " + e.getMessage());
}
}
}
				
			
Output :

Hello, Hope you having fun time learning Java.

Approach 2: Using RandomAccessFile

Writing using `RandomAccessFile`

To begin, we create a `RandomAccessFile` instance named `raf` and link it to the target file,
“SampleFile.bin”. We then set up in a “read-write” mode, which means you can both read from and
write to the file.
Now, Suppose we have a message that you want to put into the file, you first convert it into a series
of bytes using the getBytes() method.

Reading using `RandomAccessFile`

On the reading part, Again, we create a `RandomAccessFile` instance, this time setting it to “readonly” mode. This means you can only read data from the file; writing is off the table.
`raf.read()` method fetches one byte of data from the file each time you call it.
After grabbing a byte, you convert it back to a character and show it on the screen. We keep repeating
this process until there’s no more data left to read, which is indicated when `raf.read()` returns -1
Lastly, close the `raf` instance. If you’re interested to know the ways to convert an object to int in java, you can check out our artilce.

Java code for Read and write using RandomAcessFile:
				
					import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomRWIO {
public static void main(String[] args) {
// Writing binary file using RandomAccessFile
try (RandomAccessFile raf = new RandomAccessFile("SampleFile.bin", "rw")) {
String msg = "Java is best language in current scenarios";
raf.write(msg.getBytes());
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
// Reading binary file using RandomAccessFile
try (RandomAccessFile raf = new RandomAccessFile("SampleFile.bin", "r")) {
int data;
System.out.println("Binary data read using RandomAccessFile: ");
while ((data = raf.read()) != -1) {
System.out.print((char) data);
}
System.out.println();
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
				
			
Output :

Binary data read using RandomAccessFile:
Java is best language in current scenarios.

Approach 2: Using BufferedInputStream and BufferedOutputStream


Writing with `BufferedOutputStream`:


In this approach, we’re using something called `BufferedOutputStream` and `BufferedInputStream`.
We start by setting up a BufferedOutputStream named `outputStream` that’s connected to this file.
We then create a string named `data` that we want to save in file.
To make it workable for files, we convert it into a series of bytes using `getBytes()`.


Reading with `BufferedInputStream`:


For Reading, we create a BufferedInputStream called `inputStream` for the same file, “SampleFile.bin”.
The inputStream.read() method reads one byte from the file each time loop runs and when we’re
done reading, we close the `inputStream` properly.


Java code for Read and write using BufferedStream:
				
					import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class BufferedRWIO {
public static void main(String[] args) {
// Writing binary file using BufferedOutputStream
try (BufferedOutputStream outputStream = new BufferedOutputStream(
new FileOutputStream("SampleFile.bin"))) {
String data = "Isnโ€™t it a beautiful day today with Java learning";
outputStream.write(data.getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// Reading binary file using BufferedInputStream
try{
BufferedInputStream inputStream = new BufferedInputStream(new
FileInputStream("SampleFile.bin"));
int data;
System.out.println("Binary data read using BufferedInputStream: ");
while ((data = inputStream.read()) != -1) {
System.out.print((char) data);
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
				
			
Output :

Binary data read using BufferedInputStream:
Isnโ€™t it a beautiful day today with Java learning.

In case you faced difficulties in understanding the above approaches, you can always look java help online to clear all your doubts.

Conclusion:

In conclusion, understanding how to read and write binary files in Java is essential for processing different
types of data in Java. Besides the discussed approaches, another method for reading and writing
binary files is using `DataInputStream` and `DataOutputStream`.

Leave a Comment

Your email address will not be published. Required fields are marked *