I have a large int array containing image data in the format ARGB (alpha, R, G and B channels, 1 byte each). I want to save it to file in onPause()
to be able to reload it when the app i开发者_如何学JAVAs restarted. What do you think is the best way to do that?
I found the following methods:
Convert the int array to a byte array manually (see here) and then use a
FileOutputStream
to output the byte array.Wrap the array into a
java.nio.IntBuffer
and then write the object to file usingjava.io.ObjectOutputStream.writeObject()
.Write each element one at a time using
java.io.ObjectOutputStream.writeInt()
.
All these methods seem quite wasteful so there is probably another, better way. Possibly even a way to use image compression to reduce the size of the file?
From my point of view you can also use android specific storages
- Use database/content provider for storing image data
- Use out Bundle in
onSaveInstance
method
If your still want to write to a file you can use following NIO based code:
static void writeIntArray(int[] array) throws IOException {
FileOutputStream fos = new FileOutputStream("out.file");
try {
ByteBuffer byteBuff = ByteBuffer.allocate((Integer.SIZE / Byte.SIZE) * array.length);
IntBuffer intBuff = byteBuff.asIntBuffer();
intBuff.put(array);
intBuff.flip();
FileChannel fc = fos.getChannel();
fc.write(byteBuff);
} finally {
fos.close();
}
}
None of those. Some of them don't even make sense.
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
then call dos.writeInt()
as many times as necessary, then close dos
. The buffer will take away most of the pain.
Or else create an IntBuffer
and use FileChannel.write()
, but I've never been able to figure out how that works in the absence of an IntBuffer.asByteBuffer()
method. Or else create a ByteBuffer
, take it as an IntBuffer
via asIntBuffer()
, put the data in, then adjust the ByteBuffer
's length, which is another missing piece of the API, and again use FileChannel.write(ByteBuffer)
.
精彩评论