Java Files.readAllBytes example
In Java, we can use Files.readAllBytes
to read a file.
byte[] content = Files.readAllBytes(Paths.get("app.log"));
System.out.println(new String(content));
1. Text File
A Java example to write and read a normal text file.
FileExample1.java
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();
}
}
}
Output
app.log
Line 1
Line 2
2. Binary File
For binary format, we need to use Arrays.toString
to convert it to a String.
FileExample2.java
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();
}
}
}
Output
app.bin
[1, 2, 3, 4, 5]
a bit more information would have been useful. e.g does the file have to be in the same folder as the class? how do you do it if the file is in resources, absolute path or relative?
How to carry about the same process with Excel file?