Yes you are rather getting it wrong. But it easy to get it wrong ... if you don't understand the Java way of modeling textual data.

You are conflating the functionality of Reader / Writer with that of InputStream / OutputStream.

  • The former allow you to consume (read) and produce (write) characters; i.e. textual data represented using Unicode code-points.
  • The latter allow you to consume (read) and produce (write) bytes; i.e. binary or binary encoded data.

Now many Reader and Writer classes actually perform two functions at the same time; i.e. sourcing or sinking the data AND converting the data to / from characters. In some cases, you can tell the class how to do the conversion step by supplying an encoding.

By contrast an InputStream or OutputStream is a source or sink for bytes, and typically1 doesn't do any character translation.

In the case of Files.readAllBytes, the method is reading all of the bytes from a file and putting them into a byte array. It doesn't take a Charset parameter because it is not designed to do any decoding.

On the other hand, Files.readAllLines does take a Charset. That is because it is delivering the file content as an array of String objects representing the lines of the file. To when converting bytes to a Java String you need to say how the text / characters represented by the bytes are encoded.


1 - Hypothetically it could ... but you will see that Java doesn't provide classes like ReaderInputStream or WriterOutputStream. There is little need for them.

Answer from Stephen C on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › nio › file › Files.html
Files (Java Platform SE 8 )
April 21, 2026 - In most cases, the methods defined here will delegate to the associated file system provider to perform the file operations · The options parameter determines how the file is opened. If no options are present then it is equivalent to opening the file with the READ option.
🌐
Mkyong
mkyong.com › home › java › java files.readallbytes example
Java Files.readAllBytes example
April 8, 2019 - package com.mkyong; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; public class FileExample2 { public static void main(String[] args) { byte[] bytes = {1, 2, 3, 4, 5}; // Write into binary format try { Files.write(Paths.get("app.bin"), bytes, StandardOpenOption.CREATE, StandardOpenOption.APPEND); } catch (IOException x) { System.err.format("IOException: %s%n", x); } // Read try { byte[] content = Files.readAllBytes(Paths.get("app.bin")); // for binary System.out.println(Arrays.toString(content)); } catch (IOException e) { e.printStackTrace(); } } }
Top answer
1 of 2
6

Yes you are rather getting it wrong. But it easy to get it wrong ... if you don't understand the Java way of modeling textual data.

You are conflating the functionality of Reader / Writer with that of InputStream / OutputStream.

  • The former allow you to consume (read) and produce (write) characters; i.e. textual data represented using Unicode code-points.
  • The latter allow you to consume (read) and produce (write) bytes; i.e. binary or binary encoded data.

Now many Reader and Writer classes actually perform two functions at the same time; i.e. sourcing or sinking the data AND converting the data to / from characters. In some cases, you can tell the class how to do the conversion step by supplying an encoding.

By contrast an InputStream or OutputStream is a source or sink for bytes, and typically1 doesn't do any character translation.

In the case of Files.readAllBytes, the method is reading all of the bytes from a file and putting them into a byte array. It doesn't take a Charset parameter because it is not designed to do any decoding.

On the other hand, Files.readAllLines does take a Charset. That is because it is delivering the file content as an array of String objects representing the lines of the file. To when converting bytes to a Java String you need to say how the text / characters represented by the bytes are encoded.


1 - Hypothetically it could ... but you will see that Java doesn't provide classes like ReaderInputStream or WriterOutputStream. There is little need for them.

2 of 2
3

No, you only need a Charset if you want represent the bytes as a String (i.e. as text) because the meaning of the bytes depends on the encoding.

byte[] bytes = Files.readAllBytes(Paths.get("/temp.txt"));
String text = new String(bytes, StandardCharsets.ISO_8859_1);

A single byte array can represent multiple different strings depending on the encoding and the bytes in the array are independent of the encoding, so it doesn't make sense to be able to pass the encoding as an argument to this function.

🌐
TutorialsPoint
tutorialspoint.com › article › when-to-use-the-readallbytes-method-of-inputstream-in-java-9
When to use the readAllBytes() method of InputStream in Java 9?
June 12, 2025 - We will get to know the readAllBytes() ... method reads all bytes from an InputStream object at once and blocks until all remaining bytes have been read and the end of the stream is detected, or an exception is thrown....
🌐
Java Guides
javaguides.net › 2023 › 09 › java-files-readallbytes.html
Java Files readAllBytes()
September 27, 2023 - The Files.readAllBytes() method reads all the bytes from a file. The method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime error, occurs.
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › io › InputStream.html
InputStream (Java SE 11 & JDK 11 )
January 20, 2026 - public byte[] readAllBytes() throws IOException · Reads all remaining bytes from the input stream. This method blocks until all remaining bytes have been read and end of stream is detected, or an exception is thrown. This method does not close the input stream.
🌐
Sipmann
sipmann.com › article › java › java - files.readallbytes throws outofmemory
Java - Files.readAllBytes throws OutOfMemory - Sipmann
March 9, 2018 - When you need to interact with files, there's the possibility to read all bytes from the file with Files.readAllBytes. But be aware of the kinds of files your application will deal with because the Java API files have a limit for the buffer that is defined as Integer.MAX_VALUE …
Find elsewhere
🌐
Oracle
docs.oracle.com › javase › 9 › docs › api › java › io › InputStream.html
InputStream (Java SE 9 & JDK 9 )
public byte[] readAllBytes​() throws IOException · Reads all remaining bytes from the input stream. This method blocks until all remaining bytes have been read and end of stream is detected, or an exception is thrown. This method does not close the input stream.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.nio.filenio.files.readallbytes
Files.ReadAllBytes(IPath) Method (Java.Nio.FileNio) | Microsoft Learn
Microsoft makes no warranties, express or implied, with respect to the information provided here. Reads all the bytes from a file. [Android.Runtime.Register("readAllBytes", "(Ljava/nio/file/Path;)[B", "", ApiSince=26)] public static byte[]? ...
🌐
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 - The Files.readAllBytes() is the best method for using Java 7, 8 and above. It reads all bytes from a file and closes the file. The file is also closed on an I/O error or another runtime exception is thrown.
🌐
Tabnine
tabnine.com › home › code library
readAllBytes
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
GeeksforGeeks
geeksforgeeks.org › java › datainputstream-readbyte-method-in-java-with-examples
DataInputStream readByte() method in Java with Examples - GeeksforGeeks
June 5, 2020 - // Java program to illustrate // DataInputStream readByte() method import java.io.*; public class GFG { public static void main(String[] args) throws IOException { // Create byte array byte[] b = { -20, -10, 0, 10, 20 }; // Create byte array input stream ByteArrayInputStream byteArrayInputStr = new ByteArrayInputStream(b); // Convert byte array input stream to // DataInputStream DataInputStream dataInputStr = new DataInputStream( byteArrayInputStr); while (dataInputStr.available() > 0) { // Print bytes System.out.println( dataInputStr.readByte()); } } }
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

🌐
Oracle
docs.oracle.com › javaee › 7 › api › javax › jms › BytesMessage.html
BytesMessage (Java(TM) EE 7 Specification APIs)
The BytesMessage methods are based largely on those found in java.io.DataInputStream and java.io.DataOutputStream.
🌐
Kotlin
kotlinlang.org › api › core › kotlin-stdlib › kotlin.io › read-bytes.html
readBytes | Core API – Kotlin Programming Language
Gets the entire content of this file as a byte array · This method is not recommended on huge files. It has an internal limitation of 2 GB byte array size
🌐
Tutorialspoint
tutorialspoint.com › java › io › datainputstream_readbyte.htm
Java - DataInputStream readByte() method
package com.tutorialspoint; import java.io.ByteArrayInputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; public class DataInputStreamDemo { public static void main(String[] args) throws IOException { InputStream is = null; DataInputStream dis = null; byte[] buf = {65, 0, 0, 68, 69}; try { // create new byte array input stream is = new ByteArrayInputStream(buf); // create data input stream dis = new DataInputStream(is); // readByte till the data available to read while( dis.available() >0) { System.out.println(dis.readByte()); } } catch(Exception e) { // if any I/O error occurs e.printStackTrace(); } finally { // releases any associated system files with this stream if(is!=null) is.close(); if(dis!=null) dis.close(); } } }
🌐
Tutorialspoint
tutorialspoint.com › java › io › inputstream_read_byte_len.htm
Java - InputStream read(byte[] b, int off, int len) method
package com.tutorialspoint; import java.io.FileInputStream; import java.io.InputStream; public class InputStreamDemo { public static void main(String[] args) throws Exception { InputStream is = null; byte[] buffer = new byte[5]; char c; try { // new input stream created is = new FileInputStream("test.txt"); System.out.println("Characters printed:"); // read stream data into buffer is.read(buffer, 2, 3); // for each byte in the buffer for(byte b:buffer) { // convert byte to character if(b == 0) // if b is empty c = '-'; else // if b is read c = (char)b; // prints character System.out.print(c); } } catch(Exception e) { // if any I/O error occurs e.printStackTrace(); } finally { // releases system resources associated with this stream if(is!=null) is.close(); } } }