Java Snippet - Read Entire File (Including EOL Characters!) Not Line-By-Line And Without Loops!

Posted at

This nice technique reads the file 'as is',
it even keeps the internal EOL characters ('\\
', '\

It requires no external-libraries and even compatible with Java7!

Forget the entire awkward combination of InputStream, FileInputStream, FileReader, InputStreamReader and BufferedReader
and those embarrassing readline() loops!

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

 * quick complete file reader, including the EOL characters ('\\
, '\
public class Main {

public static void main(String[] args) throws IOException {
if (0 == args.length) throw new Error("no file specified..");

final String path = args[0];

final String content = new String(Files.readAllBytes(Paths.get(path)), StandardCharsets.UTF_8);


You may modify the EOL afterwards to either one you like using easy string-replace..

Similar solution but slightly slower due-to reading character by character:

public static long copyLarge(InputStream input, OutputStream output)
throws IOException {
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
long count = 0;
int n = 0;
while (-1 != (n = {
output.write(buffer, 0, n);
count += n;
return count;