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

To understand this example, you should have the knowledge of the following Java programming topics:


Before we convert a file to byte array and vice-versa, we assume we have a file named test.txt in our src folder.

Here's the content of test.txt

This is a
Test file.

Example 1: Convert File to byte[]

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;

public class FileByte {

    public static void main(String[] args) {

        String path = System.getProperty("user.dir") + "\\src\\test.txt";

        try {
            byte[] encoded = Files.readAllBytes(Paths.get(path));
            System.out.println(Arrays.toString(encoded));
        } catch (IOException e) {

        }
    }
}

v

[84, 104, 105, 115, 32, 105, 115, 32, 97, 13, 10, 84, 101, 115, 116, 32, 102, 105, 108, 101, 46]

In the above program, we store the path to the file in the variable path.

Then, inside the try block, we read all the bytes from the given path using readAllBytes() method.

Then, we use Arrays' toString() method to print the byte array.

Since, readAllBytes() might throw an IOException, we've used the try-catch block in the program.


Example 2: Convert byte[] to File

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

public class ByteFile {

    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) {

        }
    }
}

When you run the program, the contents of test.txt is copied to final.txt.

In the above program, we've used the same method as Example 1 to read all the bytes from the File stored in path. These bytes are stored in the array encoded.

We also have a finalPath where the bytes are to be written.

Then, we simply use the Files' write() method to write the encoded byte array to a File in the given finalPath.

Did you find this article helpful?