In Java, we can use Files.readAllBytes(path) to convert a File object into a byte[].

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

  String filePath = "/path/to/file";

  // file to byte[], Path
  byte[] bytes = Files.readAllBytes(Paths.get(filePath));

  // file to byte[], File -> Path
  File file = new File(filePath);
  byte[] bytes = Files.readAllBytes(file.toPath());

P.S The NIO Files class is available since Java 7.

1. FileInputStream

Before Java 7, we can initiate a new byte[] with a predefined size (same with the file length), and use FileInputStream to read the file data into the new byte[].

  // file to byte[], old and classic way, before Java 7
  private static void readFileToBytes(String filePath) throws IOException {

      File file = new File(filePath);
      byte[] bytes = new byte[(int) file.length()];

      FileInputStream fis = null;
      try {

          fis = new FileInputStream(file);

          //read file into bytes[]
          fis.read(bytes);

      } finally {
          if (fis != null) {
              fis.close();
          }
      }

  }

Or this try-with-resources version.

private static void readFileToBytes(String filePath) throws IOException {

    File file = new File(filePath);
    byte[] bytes = new byte[(int) file.length()];

    // funny, if can use Java 7, please uses Files.readAllBytes(path)
    try(FileInputStream fis = new FileInputStream(file)){
        fis.read(bytes);
    }

}

2. Apache Commons-IO

If we have Apache Commons IO, try FileUtils.

import org.apache.commons.io.FileUtils;

  //...
  File file = new File("/path/file");
  byte[] bytes = FileUtils.readFileToByteArray(file);

pom.xml

  <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.7</version>
  </dependency>

3. Convert File to byte[] and vice versa.

The below example uses the NIO Files.readAllBytes to read an image file into a byte[], and Files.write to save the byte[] into a new image file.

FileToBytes.java

package com.favtuts.io.howto;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileToBytes {
    
    public static void main(String[] args) {
        try {
            String filePath = "/home/tvt/workspace/favtuts/phone.png";

            // file to bytes[]
            byte[] bytes = Files.readAllBytes(Paths.get(filePath));

            // bytes[] to file
            Path path = Paths.get("/home/tvt/workspace/favtuts/phone2.png");
            Files.write(path, bytes);

            System.out.println("Done");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-io/howto

References

Leave a Reply

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