Reading and Writing Binary File
Reading and writing binary files in Java involves dealing with raw binary data, which is common when working with image files, audio files, or any other non-text files. Here's a detailed explanation along with examples for reading and writing binary files.
1. Reading Binary Files (Using FileInputStream
):
In this example, FileInputStream
is used to read binary data from the "input.bin" file. The read()
method reads a byte of data and returns -1 when the end of the file is reached.
2. Writing Binary Files (Using FileOutputStream
):
In this example, FileOutputStream
is used to write binary data to the "output.bin" file. The string content is converted to bytes using the getBytes()
method, and the write(byte[])
method is used to write the data.
Explanation:
Reading Binary Files:
FileInputStream
is used to read binary data from files.read()
method reads a byte of data from the input stream. It returns-1
if there is no more data because the end of the file has been reached.
Writing Binary Files:
FileOutputStream
is used to write binary data to files.Data is first converted to bytes using methods like
getBytes()
.write(byte[])
method is used to write the byte array to the output stream.
Important Notes:
Binary file reading and writing is typically used for non-text files (like images, audio, video, etc.) where raw binary data needs to be preserved.
Always handle exceptions properly to ensure your file operations are robust and can handle any potential issues that may arise during reading and writing.
These examples provide a fundamental understanding of how to read and write binary files in Java. Always close the streams after using them to release system resources.
Last updated