Question:
How do you write the contents of a file to a byte array in java?
Answer:
Files.readAllBytes(path);
Code:
import java.nio.file.*; import java.io.*; public class FileToArray { public static void main(String[] args) { byte[] bytes = null; try { Path path = Paths.get("file.txt"); bytes = Files.readAllBytes(path); } catch (IOException e) { } for(int i: bytes) { System.out.print((char)i); } } }
Output:
$ cat file.txt This is the contents of the file called file.txt $ java FileToArray This is the contents of the file called file.txt