Java – Convert File to byte[]

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;
}

 

0 0 votes
Article Rating

Hussein Terek

Owner of programmergate.com, I have a passion for software engineering and everything related to Java environment.

guest
0 Comments
Inline Feedbacks
View all comments