2

我想在一个大小为 100MB 的文件中用另一个字节数组“覆盖”或“切换”一些字节(比如文件中的前 2048 个字节)。
我不想阅读整个文件,因为我需要花费大量时间来阅读整个文件。

到目前为止我已经尝试过:

FileOutputStream out = new FileOutputStream(file);

out.getChannel().write(buffer, position);

新的缓冲区数组大小相同。

我正在使用需要这样做的 java + eclipse Android 应用程序进行开发。
如果有人可以为我写一段代码来完成这项工作,我会很高兴。

提前致谢。

4

1 回答 1

2

这会用数组的内容覆盖文件的前 2048 个字节。data

final RandomAccessFile file = new RandomAccessFile(filename, "rw");
final FileChannel channel = file.getChannel();
final byte[] data = new byte[2048];          // lets say it's got the data you want
final ByteBuffer buff = ByteBuffer.wrap(data);

channel.position(0);                         // (we were already here, but as an example)
channel.write(buff);                         // writes the entire 2028 bytes from buff
channel.force(false);                        // (superfluous if you close() afterwards)
channel.close();                             // close the file descriptor
于 2012-05-03T05:13:00.257 回答