Friday, 6 November 2015

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 data into an array of bytes.

If you are using version of Java less than 7 then 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.

If you are using Java 7 or above then you can use nio to read the data into a byte array. Files class provides a static method readAllBytes(Path path) which can be used.

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.

So let's write a Java program to see how to convert file data into bytes.

Using java.io.FileInputStream or ApacheCommonsIO

Here I am reading a file from a given location (please change the path accordingly) and then creating a fileinputstream using that file object.

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);
        for (int i = 0; i < bArray.length; i++){
           System.out.print((char) bArray[i]);
        }
        
        // Using ApacheCommons methods
        readToByteArrayUsingCommons(file);
        
    }
    
    /**
     * 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;
    }
    
    /**
     * 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);
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }
}

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

Using NIO for Java 7 or above

public class FileToByteArrayDemo {

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

That's all for this topic How to convert a file to byte array. If you have any doubt or any suggestions to make please drop a comment. Thanks!


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. How to read file from the last line in Java
  5. Zipping files in Java

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment