Example 1: Convert File to byte[]
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) {
}
}
}
v
[84, 104, 105, 115, 32, 105, 115, 32, 97, 13, 10, 84, 101, 115, 116, 32, 102, 105, 108, 101, 46]
In the above program, we store the path to the file in the variable path.
Then, inside the try block, we read all the bytes from the given path using readAllBytes() method.