Image of Java – Convert File to byte[]

ADVERTISEMENT

Table of Contents

Introduction

This tutorial shows several ways to convert a File object to a byte[] array in Java.

1- Traditional way

The traditional conversion way is through using read() method of InputStream as the following:

public static byte[] convertUsingTraditionalWay(File file)
{
    byte[] fileBytes = new byte[(int) file.length()]; 
    try(FileInputStream inputStream = new FileInputStream(file))
    {
        inputStream.read(fileBytes);
    }
    catch (Exception ex) 
    {
        ex.printStackTrace();
    }
    return fileBytes;
}

2- Java NIO

With Java 7, you can do the conversion using Files utility class of nio package:

public static byte[] convertUsingJavaNIO(File file)
{
    byte[] fileBytes = null;
    try
    {
        fileBytes = Files.readAllBytes(file.toPath());
    }
    catch (Exception ex) 
    {
        ex.printStackTrace();
    }
    return fileBytes;
}

3- Apache Commons IO

Besides JDK, you can do the conversion using Apache Commons IO library in 2 ways:

3.1. IOUtils.toByteArray()

public static byte[] convertUsingIOUtils(File file)
{
    byte[] fileBytes = null;
    try(FileInputStream inputStream = new FileInputStream(file))
    {
        fileBytes = IOUtils.toByteArray(inputStream);
    }
    catch (Exception ex) 
    {
        ex.printStackTrace();
    }
    return fileBytes;
}

3.2. FileUtils.readFileToByteArray()

public static byte[] convertUsingFileUtils(File file)
{
    byte[] fileBytes = null;
    try
    {
        fileBytes = FileUtils.readFileToByteArray(file);
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
    return fileBytes;
}

Summary

This tutorial shows several ways to convert a File object to a byte[] array in Java.

Next Steps

If you're interested in learning more about the basics of Java, coding, and software development, check out our Coding Essentials Guidebook for Developers, where we cover the essential languages, concepts, and tools that you'll need to become a professional developer.

Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, feel free to reach out to jacob@initialcommit.io.

Final Notes