Monday, 29 October 2018

How to Convert a File to Byte Array - Java Program

There are times when we need to read file content into a byte array like when we need to send the file content over the network or we need to calculate check sum using file data. So in this post we'll see various ways to convert file to a byte array in Java.

Available options for conversion

  1. Using read method of the FileInputStream class. See example.
  2. Using Files.readAllBytes() method Java 7 onward. See example.
  3. Using IOUtils.toByteArray() method provided by Apache commons IO. See example.
  4. Using FileUtils.readFileToByteArray method provided by Apache commons IO. See example.

1. File to byte[] using read method of FileInputStream

You can use java.io.FileInputStream to read file content into a byte array using the read method.

read method general structure and description as per Java docs.

public int read(byte[] b) throws IOException

Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available.

public class FileToByteArrayDemo {

    public static void main(String[] args) {
        File file = new File("F:\\NetJS\\Articles.txt");
        
        // Using java.io.FileInputStream
        byte[] bArray = readFileToByteArray(file);
        //displaying content of byte array
        for (int i = 0; i < bArray.length; i++){
           System.out.print((char) bArray[i]);
        }  
    }
    
    /**
     * This method uses java.io.FileInputStream to read
     * file content into a byte array
     * @param file
     * @return
     */
    private static byte[] readFileToByteArray(File file){
        FileInputStream fis = null;
        // Creating a byte array using the length of the file
        // file.length returns long which is cast to int
        byte[] bArray = new byte[(int) file.length()];
        try{
            fis = new FileInputStream(file);
            fis.read(bArray);
            fis.close();        
            
        }catch(IOException ioExp){
            ioExp.printStackTrace();
        }
        return bArray;
    }
}

2. File to byte array conversion using Files.readAllBytes()

Java 7 onward you can use static method readAllBytes(Path path) in the Files class for converting file to byte array.

public class FileToByteArrayDemo {

    public static void main(String[] args) {
                
        Path path = Paths.get("F:\\NetJS\\Articles.txt");
        try {
            byte[] bArray = Files.readAllBytes(path);
            // reading content from byte array
            for (int i = 0; i < bArray.length; i++){
                  System.out.print((char) bArray[i]);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
    }
}

3. Using IOUtils.toByteArray() and FileUtils.readFileToByteArray() methods

Apache commons IO also provides utility methods to read file content into a byte array.

  • IOUtils.toByteArray - takes FileInputStream object as param.
  • FileUtils.readFileToByteArray - takes File object as param.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

public class FileToByteArrayDemo {

    public static void main(String[] args) {
        File file = new File("F:\\NetJS\\Articles.txt");        
        // Using ApacheCommons methods
        readToByteArrayUsingCommons(file);     
    }
    
    /**
     * This method uses apache commons to read
     * file content into a byte array
     * @param file
     */
    private static void readToByteArrayUsingCommons(File file){
        try(FileInputStream fis = new FileInputStream(file)) {
            // Using IOUtils method, it takes FileInputStream 
            // object as param
            byte[] bArray = IOUtils.toByteArray(fis);
            for (int i = 0; i < bArray.length; i++){
               System.out.print((char) bArray[i]);
            }
            // Using FileUtils method, it takes file object
            // as param
            bArray = FileUtils.readFileToByteArray(file);
            //displaying byte array content
            for (int i = 0; i < bArray.length; i++){
                System.out.print((char) bArray[i]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }        
    }
}

Note that in the method readToByteArrayUsingCommons I have used try-with-resources which is available from Java 7. Closing the input stream will be done automatically by try-with-resources.

Recommendations for learning

  1. Java Programming Masterclass Course
  2. Java In-Depth: Become a Complete Java Engineer!
  3. Spring Framework Master Class Course
  4. Complete Python Bootcamp Course
  5. Python for Data Science and Machine Learning

That's all for this topic How to Convert a File to Byte Array - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Reading File in Java Using Scanner
  2. Reading File in Java Using BufferedReader
  3. How to Read Input From Console in Java
  4. Writing File in Java
  5. Unzipping Files in Java

You may also like -

  1. Converting String to Bytearray - Java Program
  2. Count Number of Words in a String - Java Program
  3. How to Remove Elements From an Array - Java Program
  4. Checking Number Prime or Not - Java Program
  5. final Keyword in Java With Examples
  6. How to loop through a map in Java
  7. ReentrantLock in Java concurrency
  8. What is Dependency Injection in Spring

No comments:

Post a Comment