[英]What is the best way to write an int array (image data) to file
I have a large int array containing image data in the format ARGB (alpha, R, G and B channels, 1 byte each).我有一个包含 ARGB 格式图像数据的大型 int 数组(alpha、R、G 和 B 通道,每个通道 1 个字节)。 I want to save it to file in
onPause()
to be able to reload it when the app is restarted.我想将它保存到
onPause()
文件,以便在重新启动应用程序时能够重新加载它。 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.手动将 int 数组转换为字节数组(参见此处),然后使用
FileOutputStream
输出字节数组。
Wrap the array into a java.nio.IntBuffer
and then write the object to file using java.io.ObjectOutputStream.writeObject()
.将数组包装到
java.nio.IntBuffer
,然后使用java.io.ObjectOutputStream.writeObject()
将对象写入文件。
Write each element one at a time using java.io.ObjectOutputStream.writeInt()
.使用
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从我的角度来看,您还可以使用 android 特定的存储
onSaveInstance
methodonSaveInstance
方法中使用 out Bundle If your still want to write to a file you can use following NIO based code:如果您仍然想写入文件,您可以使用以下基于 NIO 的代码:
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
.然后根据需要多次调用
dos.writeInt()
,然后关闭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.或者创建一个
IntBuffer
并使用FileChannel.write()
,但我一直无法弄清楚在没有IntBuffer.asByteBuffer()
方法的情况下它是如何工作的。 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)
.或者创建一个
ByteBuffer
,通过asIntBuffer()
将其作为IntBuffer
,将数据放入,然后调整ByteBuffer
的长度,这是 API 的另一个缺失部分,再次使用FileChannel.write(ByteBuffer)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.