The simplest approach IMO is to use Guava and its ByteStreams class:

byte[] bytes = ByteStreams.toByteArray(in);

Or for a file:

byte[] bytes = Files.toByteArray(file);

Alternatively (if you didn't want to use Guava), you could create a ByteArrayOutputStream, and repeatedly read into a byte array and write into the ByteArrayOutputStream (letting that handle resizing), then call ByteArrayOutputStream.toByteArray().

Note that this approach works whether you can tell the length of your input or not - assuming you have enough memory, of course.

Answer from Jon Skeet on Stack Overflow
🌐
How to do in Java
howtodoinjava.com › home › i/o › read file to byte[] in java
Read File to Byte[] in Java
December 14, 2022 - Learn reading data from files into a byte array in Java using NIO Files, FileInputStream, Commons IO FileUtils, and Guava ByteStreams classes.
🌐
RoseIndia
roseindia.net › java › javafile › java-read-binary-file-into-byte-array.shtml
Reading binary file into byte array in Java
import java.io.*; public class ... object File file = new File("test.zip"); //Instantiate the input stread InputStream insputStream = new FileInputStream(file); long length = file.length(); byte[] bytes = new byte[(int) length]; insputStream.read(bytes); insputStream.close(); ...
Discussions

inputstream - Reading a binary input stream into a single byte array in Java - Stack Overflow
The documentation says that one should not use available() method to determine the size of an InputStream. How can I read the whole content of an InputStream into a byte array? InputStream in; // More on stackoverflow.com
🌐 stackoverflow.com
java - Reading a binary file into byte array - Stack Overflow
I need to read a binary file and save each byte into a byte array. I've read other stackoverflow posts on this topic, but cannot figure out why mine does not work. Here is what I have: String file... More on stackoverflow.com
🌐 stackoverflow.com
January 24, 2020
java - How to read a bin file to a byte array? - Stack Overflow
Seeing the code in your question, ... gave a java answer to it ... Sign up to request clarification or add additional context in comments. ... +1 That's a nice catch Tom, ByteArrayOutputStream would suffice in this case, where we just read bytes and write bytes. If we were to write primitive types in addition DataOutputStream might be needed 2009-10-03T06:13:02.157Z+00:00 ... You're probably better off using a memory mapped file... More on stackoverflow.com
🌐 stackoverflow.com
java - Reading binary file byte by byte - Stack Overflow
I've been doing research on a java problem I have with no success. I've read a whole bunch of similar questions here on StackOverflow but the solutions just doesn't seem to work as expected. I'm ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Blogger
javarevisited.blogspot.com › 2020 › 04 › 7-examples-to-read-file-into-byte-array-in-java.html
7 Examples to Read File into a Byte Array in Java
July 28, 2021 - Hello guys, Java programmers often ... text or binary file. One example is to convert the contents of a file into String for display. Unfortunately, Java's File class, which is used to represent both files and directories, doesn't have a method say toByteArray(). It only holds path and allows you to perform certain operations like opening and closing file, but doesn't allow you to directly convert File to a byte array. Anyway, no need to worry as there are several other ways to read File into ...
🌐
CodeJava
codejava.net › java-se › file-io › how-to-read-and-write-binary-files-in-java
How to Read and Write Binary Files in Java
January 7, 2022 - java CheckPNG Diagram.pngIf the file is really a PNG image, it prints the output: Is PNG file? trueAs you can see, using FileInputStream and FileOutputStream is really good for low level binary I/O such as analyzing a file or even create your own file format. Using BufferedInputStream and BufferedOutputStream is as same as FileInputStream and FileOutputStream. The only difference is that a buffered stream uses an array of byte internally to buffer the input and output to reduce the number of calls to the native API, hence increasing IO performance.By default, both BufferedInputStream and BufferedOutputStream has an internal buffer of 8192 bytes (8KB), but we can specify a custom buffer size at initialization.All the above examples can be re-written using buffered streams just by changing the instantiation of the streams.
🌐
Kodejava
kodejava.org › how-to-read-binary-files-into-byte-arrays
How to Read Binary Files into Byte Arrays - Learn Java by Examples
August 6, 2025 - 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 ...
🌐
Mkyong
mkyong.com › home › java › java – how to convert file to byte[]
Java - How to convert File to byte[] - Mkyong.com
September 17, 2020 - In Java, we can use `Files.readAllBytes(path)` to convert a `File` object into a `byte[]`.
Find elsewhere
🌐
Javapractices
javapractices.com › topic › TopicAction.do
Java Practices->Reading and writing binary files
*/ public static void main(String... ... byte array.*/ byte[] read(String inputFileName){ log("Reading in binary file named : " + inputFileName); File file = new File(inputFileName); log("File size: " + file.length()); byte[] result = new byte[(int)file.length()]; try { ...
Top answer
1 of 4
3

Since java 7 it is not needed to read byte by byte, there are two utility function in Files:

Path path = Paths.get("C:/temp/test.txt");

// Load as binary:
byte[] bytes = Files.readAllBytes(path);
String asText = new String(bytes, StandardCharset.ISO_8859_1);

// Load as text, with some Charset:
List<String> lines = Files.readAllLines(path, StandardCharsets.ISO_8859_1);

As you want to read binary data, one would use readAllBytes.

String and char is for text. As opposed to many other programming languages, this means Unicode, so all scripts of the world may be combined. char is 16 bit as opposed to the 8 bit byte.

For pure ASCII, the 7 bit subset of Unicode / UTF-8, byte and char values are identical.

Then you might have done the following (low-quality code):

int fileLength = (int) path.size();
char[] chars = new char[fileLength];
int i = 0;
int data;
while ((data = inputStream.read()) != -1) {
    chars[i] = (char) data; // data actually being a byte
    ++i;
}
inputStream.close();

String text = new String(chars);

System.out.println(Arrays.toString(chars));

The problem you had, probably concerned the unwieldy fixed size array in java, and that a char[] still is not a String.

For binary usage, as you seem to be reading serialized data, you might like to dump the file:

int i = 0;
int data;
while ((data = inputStream.read()) != -1) {
    char ch = 32 <= data && data < 127 ? (char) data : ' ';
    System.out.println("[%06d] %02x %c%n", i, data, ch);
    ++i;
}

Dumping file position, hex value and char value.

2 of 4
1

it is simple example:

   public class CopyBytes {
    public static void main(String[] args) throws IOException {

        FileInputStream in = null;
        FileOutputStream out = null;

        try {
            in = new FileInputStream("xanadu.txt");
            out = new FileOutputStream("outagain.txt");
            int c;

            while ((c = in.read()) != -1) {
                out.write(c);
            }
        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }
}

If you want to read text(characters) - use Readers, if you want to read bytes - use Streams

🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-convert-file-to-a-byte-array
Java Program to Convert File to a Byte Array - GeeksforGeeks
July 23, 2025 - For reading streams of characters, consider using FileReader. read(byte[]) method of FileInputStream class which reads up to the length of the file and then converts bytes of data from this input stream into the byte array.
🌐
Attacomsian
attacomsian.com › blog › java-read-write-binary-files
How to Read and Write Binary Files in Java
December 5, 2019 - For better I/O performance, you should use the BufferedInputStream class as it reads a set of bytes all at once into an internal byte array buffer, reducing the number of calls to the disk, hence increasing I/O performance. By default, the internal buffer size is 8KB but we can specify a custom buffer size at the time of initialization. Here is an example that uses BufferedInputStream with default buffer size to read a binary file:
🌐
Oracle
forums.oracle.com › ords › apexds › post › fastest-way-of-reading-a-binary-file-into-a-byte-array-9966
Fastest way of reading a binary file into a byte array - Oracle Forums
June 5, 2007 - Hi I have seen there are alot of methods for reading files in Java, and in this jungle I have gotten a bit confused on which way is better to solve a specific problem. MY problem in this case is to r...
🌐
Stack Overflow
stackoverflow.com › questions › 43020815 › read-file-into-binary-byte-array-java
Read file into binary byte array - Java - Stack Overflow
The easiest thing you could do is wrap a BitSet around the byte[] so you can easily test individual bits: BitSet bitSet = BitSet.valueOf(myByteArray); boolean isBit20Set = bitSet.get(20); ... Sign up to request clarification or add additional ...
🌐
Funnel Garden
funnelgarden.com › java_read_file
How to Read Text and Binary Files in Java (ULTIMATE GUIDE)
How to read files in Java 7, 8 and 9 with examples for BufferedReader, Scanner, InputStream, InputStreamReader, FileInputStream, BufferedInputStream, FileReader, new I/O classes, Guava and Apache Commons. READ LINE BY LINE TO STRING OR BYTE ARRAY.
🌐
Delft Stack
delftstack.com › home › howto › java › java read binary files
How to Read Binary Files in Java | Delft Stack
February 2, 2024 - To solve that problem, we use the BufferedInputStream class. The BufferedInputStream class reads a set of bytes at a time into an array buffer. ... package Delfstack; import java.io.BufferedInputStream; import java.io.File; import ...
🌐
Java Code Geeks
javacodegeeks.com › home › core java
7 Examples to Read File into a byte array in Java - Java Code Geeks
April 27, 2020 - Hello guys, Java programmers often ... text or binary file. One example is to convert the contents of a file into String for display. Unfortunately, Java’s File class, which is used to represent both files and directories, doesn’t have a method say toByteArray(). It only holds path and allows you to perform certain operations like opening and closing file, but doesn’t allow you to directly convert File to a byte array. Anyway, no need to worry as there are several other ways to read File into ...
🌐
Programiz
programiz.com › java-programming › examples › convert-file-byte-array
Java Program to Convert File to byte array and Vice-Versa
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; public class FileByte { public static void main(String[] args) { String path = System.getProperty("user.dir") + "\\src\\test.txt"; try { byte[] encoded = Files.readAllBytes(Paths.get(path)); System.out.println(Arrays.toString(encoded)); } catch (IOException e) { } } }