Elegant way to read file into byte[] array in Java

JavaAndroidFileFile Io

Java Problem Overview


> Possible Duplicate:
> File to byte[] in Java

I want to read data from file and unmarshal it to Parcel. In documentation it is not clear, that FileInputStream has method to read all its content. To implement this, I do folowing:

FileInputStream filein = context.openFileInput(FILENAME);


int read = 0;
int offset = 0;
int chunk_size = 1024;
int total_size = 0;

ArrayList<byte[]> chunks = new ArrayList<byte[]>();
chunks.add(new byte[chunk_size]);
//first I read data from file chunk by chunk
while ( (read = filein.read(chunks.get(chunks.size()-1), offset, buffer_size)) != -1) {
    total_size+=read;
    if (read == buffer_size) {
         chunks.add(new byte[buffer_size]);
    }
}
int index = 0;

// then I create big buffer        
byte[] rawdata = new byte[total_size];

// then I copy data from every chunk in this buffer
for (byte [] chunk: chunks) {
    for (byte bt : chunk) {
         index += 0;
         rawdata[index] = bt;
         if (index >= total_size) break;
    }
    if (index>= total_size) break;
}

// and clear chunks array
chunks.clear();

// finally I can unmarshall this data to Parcel
Parcel parcel = Parcel.obtain();
parcel.unmarshall(rawdata,0,rawdata.length);

I think this code looks ugly, and my question is: How to do read data from file into byte[] beautifully? :)

Java Solutions


Solution 1 - Java

A long time ago:

Call any of these

byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file)
byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream input) 

From

http://commons.apache.org/io/

If the library footprint is too big for your Android app, you can just use relevant classes from the commons-io library

Today (Java 7+ or Android API Level 26+)

Luckily, we now have a couple of convenience methods in the nio packages. For instance:

byte[] java.nio.file.Files.readAllBytes(Path path)

Javadoc here

Solution 2 - Java

This will also work:

import java.io.*;

public class IOUtil {

	public static byte[] readFile(String file) throws IOException {
		return readFile(new File(file));
	}

	public static byte[] readFile(File file) throws IOException {
		// Open file
		RandomAccessFile f = new RandomAccessFile(file, "r");
		try {
			// Get and check length
			long longlength = f.length();
			int length = (int) longlength;
			if (length != longlength)
				throw new IOException("File size >= 2 GB");
			// Read file and return data
			byte[] data = new byte[length];
			f.readFully(data);
			return data;
		} finally {
			f.close();
		}
	}
}

Solution 3 - Java

If you use Google Guava (and if you don't, you should), you can call: ByteStreams.toByteArray(InputStream) or Files.toByteArray(File)

Solution 4 - Java

This works for me:

File file = ...;
byte[] data = new byte[(int) file.length()];
try {
	new FileInputStream(file).read(data);
} catch (Exception e) {
	e.printStackTrace();
}

Solution 5 - Java

Use a ByteArrayOutputStream. Here is the process:

  • Get an InputStream to read data

  • Create a ByteArrayOutputStream.

  • Copy all the InputStream into the OutputStream

  • Get your byte[] from the ByteArrayOutputStream using the toByteArray() method

Solution 6 - Java

Have a look at the following apache commons function:

org.apache.commons.io.FileUtils.readFileToByteArray(File)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionArseniyView Question on Stackoverflow
Solution 1 - JavaLukas EderView Answer on Stackoverflow
Solution 2 - JavaPaulView Answer on Stackoverflow
Solution 3 - JavaPeter ŠtibranýView Answer on Stackoverflow
Solution 4 - JavadomsomView Answer on Stackoverflow
Solution 5 - JavaVivien BarousseView Answer on Stackoverflow
Solution 6 - JavaBaScheView Answer on Stackoverflow