Converting large files to an array of bytes on Android
Developing for embedded systems comes with many challenges not faced when developing on say a desktop environment. The challenge I'm currently facing is to 开发者_如何学Cconvert a large file (possible 10-100MB) to an array of bytes while keeping in mind my limited resources (memory). Two implemetation I have been using both cause the dreaded
java.lang.OutOfMemoryError
I started by implemeting this myself:
/** Converts the given File to an array of bits. */
private byte[] fileToBytes(File file) {
InputStream input_stream = new BufferedInputStream(new FileInputStream(file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
byte[] data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data,0,data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
Then decided to use the tried and tested Apache commons-io to handle this for me, but same error. Is this something that can be done on a mobile environment such as Android, or am I out of luck?
To convert a file into a byte array you can use DatanputStream.
byte[] lData = new byte[file_length];
DataInputStream lDataIS = new DataInputStream(InputStream);
lDataIS.readFully(lData);
To properly load big files, maybe you can read them by chunk, and using proxy objects to manipulate partially loaded files.
You can't put such a big file into memory in Android, because the heap size in Android is limited to something about 16-32MB depending on device. So, you should redesign your application somehow.
精彩评论