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

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

What is Byte Array in Java ?

A byte array is a collection of bytes, often used to store binary data. It can be used to store data in memory, or to read and write data to a file or network stream. In programming languages such as C#, Java and Python, byte arrays are often used to store and manipulate binary data such as images, audio and video files.

Steps to convert File to byte array :

  1. For the file you want to convert, create a File object.
  2. Making use of the File object produced in step 1, create a FileInputStream object.
  3. Create a byte array with the file’s length in it.
  4. To read the file’s contents into the byte array, use the read() function of the FileInputStream object.
  5. FileInputStream object should be closed.

Pseudo code for the above algorithm :

// Create a File object for the file you want to convert
File file = new File("path/to/myfile.txt");

try {
    // Create a FileInputStream object using the File object
    FileInputStream fis = new FileInputStream(file);

    // Create a byte array with the length of the file
    byte[] byteArray = new byte[(int)file.length()];

    // Use the read() method of the FileInputStream object to read the contents of the file into the byte array
    fis.read(byteArray);

    // Close the FileInputStream object
    fis.close();

    // Use the byte array as needed
    // ...
} catch (IOException e) {
    // Handle the exception
    e.printStackTrace();
}

Example 1 : File to byte array

Run
import java.io.*;

public class Main {
    public static void main(String[] args) {
        // Create a File object
        File file = new File("path/to/myfile.txt");
        
        try {
            // Read the file into a byte array
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] byteArray = new byte[(int)file.length()];
            fileInputStream.read(byteArray);
            fileInputStream.close();
            
            // Use the byte array as needed
            // ...
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

For the file we wish to convert to a byte array in this example, we first build a File object. The file’s contents are then read into a byte array by creating a FileInputStream object. We utilise the read() function of the FileInputStream to read the file data into the byte array after creating a byte array with the file’s length. After closing the input stream, the byte array is ready for usage.

Example 2 : Byte array to File

Run
import java.io.*;

public class Main {
    public static void main(String[] args) {
        // Create a byte array with some data
        byte[] byteArray = { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100 };
        
        try {
            // Create a new FileOutputStream object for the file path where you want to write the file
            FileOutputStream fileOutputStream = new FileOutputStream("path/to/myfile.txt");
            
            // Write the contents of the byte array to the output stream
            fileOutputStream.write(byteArray);
            
            // Close the output stream
            fileOutputStream.close();
            
            // The byte array has been written to the file
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

In this illustration, the data that we wish to write to a file is first created as a byte array. Then, for the file location where we wish to write the file, we build a new FileOutputStream object. The data from the byte array is written to the output stream using the FileOutputStream’s write() function. After writing the byte array to the file, we finally close the output stream.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription