Java IO Tutorial

Java – How to convert File to byte[]

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.mkyong.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/mkyong/test/phone.png";

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

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

            System.out.println("Done");

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

    }

}

Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-io

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
9 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
dazz
6 years ago

try {

byte[] bFile = Files.readAllBytes(Paths.get(“/home/input_test.png”));

// save byte[] into a file
Path path = Paths.get(“/home/output_test.png”);

// The CREATE option is necessary. without it, the file is created with zero bytes the first time
// a write is attempted. The 2nd write works OK.
// With CREATE added, the write works first time whether the file exists or not.
//This next line replaces all of readBytesFromFile
Files.write(path, bFile,StandardOpenOption.CREATE);
System.out.println(“Done”);

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

}

Daniel Souza
9 years ago

//Java 7 Files class:
byte[] data = Files.readAllBytes(file.getPath());

Feiyu Zhou
9 years ago
Reply to  Daniel Souza

toPath()

mkyong
7 years ago
Reply to  Feiyu Zhou

Article is updated with java.nio example, thanks for your suggestion.

Omar
1 year ago

So usefull!!

Facundo
1 year ago

Hello ! Thanks for this, it is really helpful. Anyway, I am not able to make it work with a PDF file. The copied file is completely blank. Do you have a way to make this work ? With other file types is working fine. Thanks !!!

Noor Hossain
1 year ago

can I create bytes [] of database files, like mydb.db file

m asad
2 years ago

hello , can you please help me I am converting bytes array to audio file but it is not working?