HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Java / I/O / Java Read File to Byte Array

Java Read File to Byte Array

In Java, readind a file to byte array may be needed into various situations. For example, passing the information through the network as well as other APIs for further processing.

Let’s learn about a few ways of reading data from files into a byte array in Java.

1. Files.readAllBytes() – Java 8

Files.readAllBytes() is best method if you are using Java 7, 8 and above.

Example 1: Reading file to byte[] in Java 8

public class ContentToByteArrayExample
{
   public static void main(String[] args)
   {
      Path path = Paths.get("C:/temp/test.txt");
      byte[] data = Files.readAllBytes(path);
   }
}

Read More: 3 ways to read files using Java NIO

2. FileInputStream – Java 6

Use java.io.FileInputStream for reading the content of a file in Java 6.

Example 2: Reading a file byte by byte

import java.io.File;
import java.io.FileInputStream;

public class ContentToByteArrayExample
{
   public static void main(String[] args)
   {
      
      File file = new File("C:/temp/test.txt");
      
      readContentIntoByteArray(file);
   }

   private static byte[] readContentIntoByteArray(File file)
   {
      FileInputStream fileInputStream = null;
      byte[] bFile = new byte[(int) file.length()];
      try
      {
         //convert file into array of bytes
         fileInputStream = new FileInputStream(file);
         fileInputStream.read(bFile);
         fileInputStream.close();
         for (int i = 0; i < bFile.length; i++)
         {
            System.out.print((char) bFile[i]);
         }
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }
      return bFile;
   }
}

3. FileUtils, IOUtils – Apache Commons IO

Another good way to read data into a byte array is in apache commons IO library.

Example 3: Reading an entire file into byte[]

//Using FileUtils.readFileToByteArray()
byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file)

//Using IOUtils.toByteArray
byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream input) 

4. Files, ByteStreams – Guava

Another good way to read data into byte array is in Google Guava library.

Example 4: Reading an entire file into byte[]

//Using Files.toByteArray()
byte[] com.google.common.io.Files.toByteArray(File file)

//Using ByteStreams.toByteArray
byte[] com.google.common.io.ByteStreams.toByteArray(InputStream is)

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Binh Thanh Nguyen

    October 16, 2015

    Thanks, nice tips. Help me a lot

  2. sri

    November 4, 2014

    1 )Write a code which will construct a line for me two points ( .————————.) ?
    Output should be “these line is made my these two points”

    2) I have one Bottle object.I want to design all the oops concepts using that object can anyone explain me ?

Comments are closed on this article!

Search Tutorials

Java IO

  • Java IO Introduction
  • Java How IO works?
  • Java IO vs NIO
  • Java Create File
  • Java Write to File
  • Java Append to File
  • Java Read File
  • Java Read File to String
  • Java Read File to Byte[]
  • Java Make File Read Only
  • Java Copy File
  • Java Copy Directory
  • Java Delete Directory
  • Java Current Working Directory
  • Java Read/Write Properties File
  • Java Read File from Resources
  • Java Read File from Classpath
  • Java Read/Write UTF-8 Data
  • Java Check if File Exist
  • Java Create Temporary File
  • Java Write to Temporary File
  • Java Delete Temporary File
  • Java Read from Console
  • Java Typesafe input using Scanner
  • Java Password Protected Zip
  • Java Unzip with Subdirectories
  • Java Generate SHA/MD5
  • Java Read CSV File
  • Java InputStream to String
  • Java String to InputStream
  • Java OutputStream to InputStream
  • Java InputStreamReader
  • Java BufferedReader
  • Java FileReader
  • Java LineNumberReader
  • Java StringReader
  • Java FileWriter
  • Java BufferedWriter
  • Java FilenameFilter
  • Java FileFilter

Java Tutorial

  • Java Introduction
  • Java Keywords
  • Java Flow Control
  • Java OOP
  • Java Inner Class
  • Java String
  • Java Enum
  • Java Collections
  • Java ArrayList
  • Java HashMap
  • Java Array
  • Java Sort
  • Java Clone
  • Java Date Time
  • Java Concurrency
  • Java Generics
  • Java Serialization
  • Java Input Output
  • Java New I/O
  • Java Exceptions
  • Java Annotations
  • Java Reflection
  • Java Garbage collection
  • Java JDBC
  • Java Security
  • Java Regex
  • Java Servlets
  • Java XML
  • Java Puzzles
  • Java Examples
  • Java Libraries
  • Java Resources
  • Java 14
  • Java 12
  • Java 11
  • Java 10
  • Java 9
  • Java 8
  • Java 7

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces