Java program to convert file to byte array and vice versa
Here is a Java program to convert a file to a byte array and vice-versa:
import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class ConvertFileToByteArrayAndByteArrayToFile { public static void main(String[] args) throws IOException { // Convert file to byte array File file = new File("example.txt"); byte[] fileContent = Files.readAllBytes(file.toPath()); System.out.println("File content as byte array: " + new String(fileContent)); // Convert byte array to file Path path = Files.write(Path.of("newfile.txt"), fileContent); System.out.println("File content written to file: " + path); } }
This program first creates a File
object representing a text file, "example.txt". It then reads the contents of the file into a byte array using the Files.readAllBytes()
method. The resulting byte array contains the contents of the file in binary format.
Next, the program writes the byte array to a new file using the Files.write()
method. The Files.write()
method writes the contents of the byte array to the specified file path, and returns a Path
object representing the newly created file.
Note that this program assumes that the file contains text data, and so it converts the byte array to a string using the String
constructor. If the file contains binary data, you would need to use a different method to convert the byte array to a more appropriate format, such as Base64 encoding. Similarly, if you want to convert a byte array back to a file, you will need to know the format of the original file so that you can create the new file with the correct extension and content type.