🌐
Mkyong
mkyong.com › home › java › java files.readallbytes example
Java Files.readAllBytes example - Mkyong.com
April 8, 2019 - package com.mkyong.calculator; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; public class FileExample1 { public static void main(String[] args) { Charset utf8 = StandardCharsets.UTF_8; List<String> list = Arrays.asList("Line 1", "Line 2"); // Write try { Files.write(Paths.get("app.log"), list, utf8, StandardOpenOption.CREATE, StandardOpenOption.APPEND); } catch (IOException x) { System.err.format("IOException: %s%n", x); } // Read try { byte[] content = Files.readAllBytes(Paths.get("app.log")); System.out.println(new String(content)); // for binary //System.out.println(Arrays.toString(content)); } catch (IOException e) { e.printStackTrace(); } } }
🌐
GeeksforGeeks
geeksforgeeks.org › c# › file-readallbytes-method-in-csharp-with-examples
File.ReadAllBytes() Method in C# with Examples - GeeksforGeeks
April 28, 2025 - // C# program to illustrate the ... a file string path = @"file.txt"; // Calling the ReadAllBytes() function byte[] readText = File.ReadAllBytes(path); foreach(byte s in readText) { // Printing the binary array value ...
🌐
Attacomsian
attacomsian.com › blog › java-files-readallbytes-example
How to read a file using Files.readAllBytes() in Java
December 11, 2019 - try { // read all bytes byte[] bytes = Files.readAllBytes(Paths.get("input.txt")); // convert bytes to string String content = new String(bytes); // print contents System.out.println(content); } catch (IOException ex) { ex.printStackTrace(); ...
🌐
Java Guides
javaguides.net › 2023 › 09 › java-files-readallbytes.html
Java Files readAllBytes()
September 27, 2023 - import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class ReadAllBytesExample { public static void main(String[] args) { Path path = Paths.get("sample.txt"); try { byte[] fileBytes = Files.readAllBytes(path); String fileContent = new String(fileBytes); System.out.println(fileContent); } catch (IOException e) { System.out.println("Error reading the file: " + e.getMessage()); } } } Assuming sample.txt contains: Hello, World! The console output will be: Hello, World! In this example, Files.readAllBytes() is used to read all the bytes from the file sample.txt.
🌐
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 - import java.nio.*; import java.nio.file.*; import java.io.*; import java.util.stream.*; import java.nio.charset.StandardCharsets; public class ReadAllBytesMethodTest { public static void main(String args[]) { try(InputStream stream = Files.newInputStream(Paths.get("C://Temp//Technology.txt"))) { // Convert stream to string String contents = new String(stream.readAllBytes(), StandardCharsets.UTF_8); // To print the string content System.out.println(contents); } catch(IOException ioe) { ioe.printStackTrace(); } } }
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
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.
🌐
Java Tips
javatips.net › api › java.nio.file.files.readallbytes
Java Examples for java.nio.file.Files.readAllBytes - Javatips.net
*/ @Test public void testTokenize_File() throws Exception { System.out.println("tokenize"); //java.net.URL url = this.class.getResource("test/resources/tokenizer/test-input.txt"); //File f=FileUtils.toFile(this.getClass().getResource("/tokenizer/test-input.txt.tokenized")); File f_in = new File(this.getClass().getResource("/tokenizer/test-input.txt").toURI()); File f_out = new File(this.getClass().getResource("/tokenizer/test-input.txt.tokenized").toURI()); String expResultString = new String(java.nio.file.Files.readAllBytes(f_out.toPath()), "UTF-8"); String inputString = new String(java.nio.file.Files.readAllBytes(f_in.toPath()), "UTF-8"); // tokenize without sentence splitting Tokenizer_PTB_Rulebased instance = new Tokenizer_PTB_Rulebased(false); String result = instance.tokenize(inputString); assertEquals(expResultString, result); //assertArrayEquals }
🌐
Dot Net Perls
dotnetperls.com › file-readallbytes
C# - File.ReadAllBytes, Get Byte Array From File - Dot Net Perls
BinaryReader ExampleBinaryWriter Typebyte Array ExampleException HandlingFile HandlingMemoryStream Exampleusing Keyword · This C# method returns a byte array. ReadAllBytes() is simple to call—it receives a file name and returns the file data.
Find elsewhere
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.io.file.readallbytes
File.ReadAllBytes(String) Method (System.IO) | Microsoft Learn
Opens a binary file, reads the contents of the file into a byte array, and then closes the file. public: static cli::array <System::Byte> ^ ReadAllBytes(System::String ^ path);
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › microsoft.visualbasic.fileio.filesystem.readallbytes
FileSystem.ReadAllBytes(String) Method (Microsoft.VisualBasic.FileIO) | Microsoft Learn
This example reads from the file C:/Documents and Settings/selfportrait.jpg. My.Computer.FileSystem.ReadAllBytes( "C:/Documents and Settings/selfportrait.jpg")
🌐
Blogger
javarevisited.blogspot.com › 2015 › 02 › how-to-read-file-in-one-line-java-8.html
How to read a File in One Line in Java? Files.readAllLines() Example Tutorial
Our example uses a new Files class which was introduced in JDK 1.7, the java.nio.file.Files class contains lots of utility methods to deal with files in Java e.g. checking whether a file is hidden or to check if a file is read-only. You can use Files.readAllBytes(Path) to read a complete file in memory.
🌐
Mkyong
mkyong.com › home › java › java – how to convert file to byte[]
Java - How to convert File to byte[] - Mkyong.com
September 17, 2020 - private static void readFileTo...7</version> </dependency> The below example uses the NIO Files.readAllBytes to read an image file into a byte[], and Files.write to save the byte[] into a new image file....
🌐
Coderwall
coderwall.com › p › gonxog › c-readallbytes-performance
C# ReadAllBytes Performance (Example)
February 25, 2016 - static byte[] readBytes(string file_name, int buffer) { List<byte[]> dirtybytes = new List<byte[]>(); using (BinaryReader b = new BinaryReader(File.Open(file_name, FileMode.Open, FileAccess.Read))) { //hold position counters int pos = 0; int length = (int)b.BaseStream.Length; while (pos < length) { //read the bytes dirtybytes.Add(b.ReadBytes(buffer)); //increment the position pos += buffer; } } //get the complete byte array return dirtybytes.SelectMany(x => x).ToArray(); }
🌐
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 - Path path = Paths.get("C:/temp/test.txt"); byte[] data = Files.readAllBytes(path);
🌐
Csharp-extension
csharp-extension.com › en › method › 1002000 › fileinfo-readallbytes
FileInfo - ReadAllBytes | C# Extension Methods
Online-Example · Opens a binary file, reads the contents of the file into a byte array, and then closes the file. Try it · public static string FileName = "test.txt"; public static void Main() { SaveFile(); // C# Extension Method: FileInfo - ReadAllBytes var bytes = FileName.ToFileInfo()...
🌐
Mkyong
mkyong.com › home › java › how to read a file in java
How to read a file in Java - Mkyong.com
July 17, 2020 - import com.mkyong.io.utils.ResourceHelper; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; public class ReadFile3 { public static void main(String[] args) throws IOException { String fileName = "/home/mkyong/app.log"; byte[] bytes = Files.readAllBytes(Paths.get(fileName)); String content = new String(bytes, StandardCharsets.UTF_8); System.out.println(content); } } 4.1 This example uses Files.readAllLines to read a file into a List<String>, if the file size is larger than the running JVM heap size, it will throw java.lang.OutOfMemoryError: Java heap space.
Top answer
1 of 4
36

This has to do with character encoding. Computers only deal with numbers. To store text, the characters in the text have to be converted to and from numbers, using some scheme. That scheme is called the character encoding. There are many different character encodings; some of the well-known standard character encodings are ASCII, ISO-8859-1 and UTF-8.

In the first example, you read all the bytes (numbers) in the file and then convert them to characters by passing them to the constructor of class String. This will use the default character encoding of your system (whatever it is on your operating system) to convert the bytes to characters.

In the second example, where you use Files.lines(...), the UTF-8 character encoding will be used, according to the documentation. When a sequence of bytes is found in the file that is not a valid UTF-8 sequence, you'll get a MalformedInputException.

The default character encoding of your system may or may not be UTF-8, so that can explain a difference in behaviour.

You'll have to find out what character encoding is used for the file, and then explicitly use that. For example:

String content = new String(Files.readAllBytes(Paths.get("_template.txt")),
        StandardCharsets.ISO_8859_1);

Second example:

Stream<String> lines = Files.lines(Paths.get("_template.txt"),
        StandardCharsets.ISO_8859_1);
2 of 4
6

To complement Jesper's answer, what happens here (and is undocumented!) is that Files.lines() creates a CharsetDecoder whose policy is to reject invalid byte sequences; that is, its CodingErrorAction is set to REPORT.

This is unlike what happens for nearly all other Reader implementations provided by the JDK, whose standard policy is to REPLACE. This policy will result in all unmappable byte sequences to emit a replacement character (U+FFFD).

🌐
IBM
ibm.com › docs › en › rpa › 21.0.x
Read All Bytes - IBM Documentation
May 16, 2023 - defVar --name bytesList --type List --innertype Byte // Download the following file to execute the command. readAllBytes --filepath "fileReadAllBytes.jpg" bytesList=value logMessage --message "${bytesList}" --type "Info" // Show in the console ...