Image of Java – Convert byte[] to File

ADVERTISEMENT

Introduction

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

1- Traditional way

The traditional way of doing the conversion is through using FileOutputStream as the following:

public static File convertUsingOutputStream(byte[] fileBytes)
{
    File f = new File("C:\\Users\\user\\Desktop\\output\\myfile.pdf");
    try (FileOutputStream fos = new FileOutputStream(f)) {
        fos.write(fileBytes);
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
    return f;
}

2- Java NIO

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

public static File convertUsingJavaNIO(byte[] fileBytes)
{
    File f = new File("C:\\Users\\user\\Desktop\\output\\myfile.pdf");
    try
    {
        Files.write(f.toPath(), fileBytes);
    }
    catch (Exception ex) 
    {
        ex.printStackTrace();
    }    
    return f;
}

3- Apache Commons IO

Besides JDK, you can do the conversion using Apache Common IO library as the following:

public static File convertUsingCommonsIO(byte[] fileBytes)
{
    File f = new File("C:\\Users\\user\\Desktop\\output\\myfile.pdf");
    try
    {
        FileUtils.writeByteArrayToFile(f, fileBytes);
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }    
    return f;
}

Summary

This tutorial shows several ways to convert a byte[] array to File 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.