Skip to content
Related Articles

Related Articles

Improve Article

Java Program to Convert File to a Byte Array

  • Last Updated : 17 Jun, 2021

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 ‘gfg.txt’ which is present on the local directory. Let the content inside the file be as shown below:

Geeks for Geeks.

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:

  1. Using read(byte[]) method of FileInputStream class 
  2. Using Files.readAllBytes() method 

Method 1: Using read(byte[]) method of FileInputStream class 

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:

  1. Create an instance of File Input Stream with the file path.
  2. Create a byte array of the same length of the file.
  3. Read that file content to an array
  4. Print the byte array
  5. Close the instance of file input stream as it is a good practice in order to avoid any exception or error been faced during runtime and to release the memory resources making our program optimized leading to faster execution.

Example

Java




// Java Program to Convert File to a Byte Array
// Using  read(byte[]) method
  
// Importing required classes
import java.io.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
  
// Main class
public 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 arrray
        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("C:\\Users\\HP\\Desktop\\gfg.txt");
  
        // 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: 

[71, 101, 101, 107, 115, 32, 102, 111, 114, 32, 71, 101, 101, 107, 115, 46, 10]

Now let us dwell on another way of achieving the same.

Method 2: Using Files.readAllBytes() method

 java.nio.file.Files class having pre-defined readAllBytes() method which reads all the bytes from a file.

Procedure:

  1. Take a text file path
  2. Convert that file into a byte array by calling Files.readAllBytes().
  3. Print the byte array.

Example

Java




// Java Program to Convert File to a Byte Array
// Using Files.readAllBytes() method
  
// Importing required classes
import 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 class
public 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("C:\\Users\\HP\\Desktop\\gfg.txt");
  
        // Now convert  file into a byte array
        // using Files.readAllBytes() method
        byte[] arr = Files.readAllBytes(path);
  
        // Lastly print the above byte array
        System.out.println(Arrays.toString(arr));
    }
}

Output: 

[71, 101, 101, 107, 115, 32, 102, 111, 114, 32, 71, 101, 101, 107, 115, 46, 10]

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :