Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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? :)

like image 323
Arseniy Avatar asked May 19 '11 11:05

Arseniy


People also ask

Can you print [] byte?

You can simply iterate the byte array and print the byte using System. out. println() method.

What is Bytearray Java?

A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..

How do I read bytes from a file?

ReadAllBytes(String) is an inbuilt File class method that is used to open a specified or created binary file and then reads the contents of the file into a byte array and then closes the file. Syntax: public static byte[] ReadAllBytes (string path);


1 Answers

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

like image 110
Lukas Eder Avatar answered Sep 21 '22 13:09

Lukas Eder