How to convert a file into byte array in Java

In this tutorial, we are going to see how to convert a file into byte array in Java. Before converting a file into byte[] array, suppose we have a file named “file.txt”. Here is the content of the “file.txt” file.

Welcome to StackHowTo!


Program to convert a file into byte array in Java:
import java.nio.file.*;
import java.util.Arrays;

public class Main {

    public static void main(String[] args) {

        String file = "C:\\Users\\PC\\Desktop\\file.txt";

        try {
            byte[] arr = Files.readAllBytes(Paths.get(file));
        } catch (IOException e) {


[111, 128, 69, 658, 142, 110, 23, 147, 896, 325, 123, 13, 36, 912, 98, 120]

In the code above, we store the path to the file in the “file” variable. Then, inside the try block, we read all the bytes of the given file using the readAllBytes() method. Next, we use the toString() method to display the array of byte[].
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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