Convert Byte Array File Java Vice Versa

Convert Byte Array File Java Vice Versa

If you want to convert byte array to file and vice versa using java you could use java.nio.file.Files.readAllBytes() to read all bytes from file and convert back byte array to file again using java.nio.file.Files.write(). Please have example below:

  • ConvertByteArrayToFile.java
package com.javahonk;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class ConvertByteArrayToFile {
	
	private final static String READ_TO_FILE_NAME = "C:\\JavaHonk\\File\\ReadFile.txt";
	private final static String WRITE_TO_FILE_NAME = "C:\\JavaHonk\\File\\WriteFile.txt";
		
	public static void main(String args[]) throws IOException {

		Path path = Paths.get(READ_TO_FILE_NAME);
		byte fileInByteArray[] = Files.readAllBytes(path);
		
		path = Paths.get(WRITE_TO_FILE_NAME);
		
		Files.write(path, fileInByteArray);
		System.out.println("File converted successfully");
		
	}	

}
  •  Output:

Convert Byte Array File Java Vice Versa

  • For more information to convert byte array to file vice versa please refer oracle documentation here

Leave a Reply

Your email address will not be published. Required fields are marked *