Java Program to Convert File to a Byte Array

22 Apr, 2022
Here, we will go through the different ways to convert file to byte array in Java.
Note: Keep a check that prior doing anything first. Create a file on the system repository to deal with our program\writing a program as we will be accessing the same directory through our programs.
Methods:
Using read(byte[]) method of FileInputStream classUsing Files.readAllBytes() method 
Using read(byte[]) method of FileInputStream class
Using Files.readAllBytes() method 
FileInputStream is useful to read data from a file in the form of a sequence of bytes. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. read(byte[]) method of FileInputStream class which reads up to the length of the file and then converts bytes of data from this input stream into the byte array.
Procedure:
Create an instance of File Input Stream with the file path.Create a byte array of the same length as the file.Read that file content to an array.Print the byte array.Close the instance of the file input stream as it is a good practice in order to avoid any exception or error being faced during runtime and to release the memory resources making our program optimized leading to faster execution.
Create an instance of File Input Stream with the file path.
Create a byte array of the same length as the file.
Read that file content to an array.
Print the byte array.
Close the instance of the file input stream as it is a good practice in order to avoid any exception or error being faced during runtime and to release the memory resources making our program optimized leading to faster execution.
Implementation: In order to illustrate the conversion of a text file present in the local directory on a machine to the byte array, we will be considering a random file named say it be ‘demo.rtf’ which is present in the local directory. 
Example:
Java
// Java Program to Convert File to a Byte Array// Using read(byte[]) Method  // Importing required classesimport java.io.*;import java.io.File;import java.io.FileInputStream;import java.io.IOException;import java.util.Arrays;  // Main classpublic class GFG {      // Method 1    // To convert file to byte array    public static byte[] method(File file)        throws IOException    {          // Creating an object of FileInputStream to        // read from a file        FileInputStream fl = new FileInputStream(file);          // Now creating byte array of same length as file        byte[] arr = new byte[(int)file.length()];          // Reading file content to byte array        // using standard read() method        fl.read(arr);          // lastly closing an instance of file input stream        // to avoid memory leakage        fl.close();          // Returning above byte array        return arr;    }      // Method 2    // Main driver method    public static void main(String[] args)        throws IOException    {          // Creating an object of File class and        // providing local directory path of a file        File path = new File(            "/Users/mayanksolanki/Desktop/demo.rtf");          // Calling the Method1 in main() to        // convert file to byte array        byte[] array = method(path);          // Printing the byte array        System.out.print(Arrays.toString(array));    }}
 Output:
java.nio.file.Files class has pre-defined readAllBytes() method which reads all the bytes from a file.
Procedure: 
Take a text file pathConvert that file into a byte array by calling Files.readAllBytes().Print the byte array.
Take a text file path
Convert that file into a byte array by calling Files.readAllBytes().
Print the byte array.
Example:
Java
// Java Program to Convert File to a Byte Array// Using Files.readAllBytes() Method  // Importing required classesimport java.io.*;import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.util.Arrays;  // Main classpublic class GFG {      // Main driver method    public static void main(String[] args)        throws IOException    {          // Creating an object of Path class and        // assigning local directory path of file to it        Path path = Paths.get(            "/Users/mayanksolanki/Desktop/demo.rtf");          // Converting the file into a byte array        // using Files.readAllBytes() method        byte[] arr = Files.readAllBytes(path);          // Printing the above byte array        System.out.println(Arrays.toString(arr));    }}
Output: 
sweetyty
solankimayank
Java-Array-Programs
Java-Files
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array