To read a binary file into a byte array in Java, you can use various ways such as Files.readAllBytes(), FileInputStream, or DataInputStream. Below is an explanation of the most common methods.
Using Files.readAllBytes() (Java NIO)
This is the simplest and most efficient way if you’re using Java 7 or later. The Files.readAllBytes() method reads all the bytes from a file into a byte array.
package org.kodejava.nio;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
public class BinaryFileToByteArray {
public static void main(String[] args) {
Path filePath = Paths.get("path/to/file.bin");
try {
byte[] fileBytes = Files.readAllBytes(filePath);
System.out.println("File read successfully, size: " + fileBytes.length + " bytes");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Using FileInputStream
Another common way is to use FileInputStream in combination with a buffer.
package org.kodejava.nio;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class BinaryFileToByteArray {
public static void main(String[] args) {
File file = new File("path/to/file.bin");
try (FileInputStream fis = new FileInputStream(file)) {
byte[] fileBytes = new byte[(int) file.length()];
fis.read(fileBytes); // Read file into byte array
System.out.println("File read successfully, size: " + fileBytes.length + " bytes");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Using DataInputStream
Using DataInputStream with a FileInputStream allows you to work with primitive types and is useful when dealing with binary files.
package org.kodejava.nio;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class BinaryFileToByteArrayExam3 {
public static void main(String[] args) {
File file = new File("path/to/file.bin");
try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {
byte[] fileBytes = new byte[(int) file.length()];
dis.readFully(fileBytes); // Reads the file fully into byte array
System.out.println("File read successfully, size: " + fileBytes.length + " bytes");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Choosing a Method
Files.readAllBytesis the easiest and most concise for modern Java.FileInputStreamandDataInputStreamprovide more flexibility if you need finer control over the file reading process.
Note: Always handle exceptions properly, especially in cases where the file may not exist or the application might not have the necessary permissions.
