Write a Java Program to Convert File to byte array and Vice-Versa

In Java, converting a file to a byte array or vice versa can be done using built-in classes and methods from the Java standard library.

This is useful when you need to transmit a file over a network, store it in a database, or manipulate its contents in memory.

In this tutorial, we’ll cover how to perform these operations using Java code.


Converting File to Byte Array

To convert a file to a byte array, you first need to read the file into memory using an InputStream.

Here’s a sample code that does this:

import java.io.*;

public class FileToByteArrayExample {
  public static void main(String[] args) {
    try {
      File file = new File("myfile.txt");
      byte[] fileContent = new byte[(int) file.length()];
      FileInputStream fis = new FileInputStream(file);
      fis.read(fileContent);
      fis.close();
      System.out.println("File converted to byte array successfully!");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

In this code, we first create a File object representing the file we want to convert.

Then, we create a byte array with the same size as the file using the length() method of the File object.

Next, we create a FileInputStream object to read the contents of the file into the byte array.

Finally, we close the stream and print a message to indicate that the conversion was successful.

Converting Byte Array to File

To convert a byte array to a file, you first need to create a File object representing the destination file, and then write the contents of the byte array to the file using an OutputStream.

Here’s a sample code that does this:

import java.io.*;

public class ByteArrayToFileExample {
  public static void main(String[] args) {
    try {
      byte[] fileContent = "This is a byte array.".getBytes();
      File file = new File("mynewfile.txt");
      FileOutputStream fos = new FileOutputStream(file);
      fos.write(fileContent);
      fos.close();
      System.out.println("Byte array converted to file successfully!");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

In this code, we first create a byte array containing the contents of the file we want to create.

Then, we create a File object representing the destination file.

Next, we create a FileOutputStream object to write the contents of the byte array to the file.

Finally, we close the stream and print a message to indicate that the conversion was successful.


Conclusion

In this tutorial, we covered how to convert a file to a byte array and vice versa using Java code.

These operations are commonly used when dealing with file data in memory, and can be useful in a variety of scenarios.

With the built-in classes and methods provided by the Java standard library, performing these operations is straightforward and simple.