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? :)
You can simply iterate the byte array and print the byte using System. out. println() method.
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..
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);
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With