Convert File to Byte Array in Java

Exercise:

Write a Java Program to convert file to byte array.

Click Here to View the Solution!
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Paths;
 import java.util.Arrays;
  
 public class FileToByte {
    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) {
       }
     }
 } 
//CONTENT OF test.txt
//This is a Test file.
Click Here to View the Output!
[84, 104, 105, 115, 32, 105, 115, 32, 97, 13, 10, 84, 101, 115, 116, 32, 102, 105, 108, 101, 46]

Click Here to View the Explanation!
  • In this program, a variable called path stores the file location.
  • All the bytes are read through readAllBytes() method with the help of the path provided inside the try block.
  • For displaying the byte array, an array method known as toString() is utilized.
  • There is a probability of IOException to arise in relation to the readAllLines() method for which exception handling must be incorporated in the try-catch block.

%d bloggers like this: