Convert Byte[] to File in Java

Exercise:

Write a Java Program to convert byte array to file .

Click Here to View the Solution!
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Paths;
  
 public class ByteToFile {
     public static void main(String[] args) {
  
         String path = System.getProperty("user.dir") + "\\src\\test.txt";
         String finalPath = System.getProperty("user.dir") + "\\src\\final.txt";
         try {
             byte[] encoded = Files.readAllBytes(Paths.get(path));
             Files.write(Paths.get(finalPath), encoded);
         } catch (IOException e){
         }
     }
 } 
Click Here to View the Output!
When you run the program, the contents of test.txt get copied to final.txt.
Click Here to View the Explanation!
  • Upon executing this program, all the data is copied from test.txt to final.txt.
  • 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 and the variable ‘encoded’ is used for storing these bytes.
  • These bytes will be written in the variable finalPath.
  • Write() method of the File class is utilized for writing this array to the file as per specified in the finalPath.