我很难理解MappedByteBuffer的读写。下面是我所拥有的类,它读取本地文件的内容,并准备反转其内容。我使用的是java版本8。
public class MappedByteBufferExample {
public static void main(String[] args) {
try (RandomAccessFile file = new RandomAccessFile("resources\\MappedByteBufferExample.txt", "rw");
FileChannel fileChannel = file.getChannel();) {
long size = fileChannel.size();
MappedByteBuffer mappedBuffer = fileChannel.map(MapMode.READ_WRITE, 0, size);
System.out.println("Text from File : -----");
while (mappedBuffer.remaining() > 0) {
System.out.print((char) mappedBuffer.get());
}
System.out.println("\n");
for (int index = 0; index < (mappedBuffer.limit() / 2); index++) {
byte b1 = mappedBuffer.get(index);
byte b2 = mappedBuffer.get(mappedBuffer.limit() - index - 1);
mappedBuffer.put(index, b2);
mappedBuffer.put(mappedBuffer.limit() - index - 1, b1);
}
//mappedBuffer.force(); I tried with this but no change in result.
//mappedBuffer.load(); I tried with this but no change in result.
mappedBuffer.load();
mappedBuffer.flip();
System.out.println("Text Reversed : -----");
while (mappedBuffer.remaining() > 0) {
System.out.print((char) mappedBuffer.get());
}
} catch (IOException e) {
e.printStackTrace();
}
}}文件的内容是-玫瑰是红色的!
在将此文件输出到控制台时,如下所示:
档案文本:
玫瑰是红色的!
颠倒:
!deR era sesoR
但是文件的内容没有变化。在第二次执行此程序时,控制台的输出是:
档案文本:
!deR era sesoR
颠倒:
玫瑰是红色的!
该文件的内容仍未更改。我尝试了load()和force()方法一次一个,两者兼而有之,但是这里的结果没有变化,这是我的问题:
1)为什么不更改本地文件的内容?
2)该程序需要哪些更改才能将数据写入文件?
3)为什么/如何在第二次迭代中读取反转的文本,尽管文件内容没有反转?
发布于 2016-10-02 12:50:28
文件的内容将被更改。通常的编辑器(如notepad++或eclipse)不会注意更改,因为使用RandomAccessFile不会更改文件的日期时间。但是,如果您真的在运行后手动重新加载文件,您应该会看到这些更改。
发布于 2016-10-04 15:57:14
既然你的实际问题已经解决了,一些评论:
RandomAccessFile绕道来打开FileChannelCharset API允许您正确地将ByteBuffer的内容转换为字符(将byte转换为char仅适用于当前ByteBuffer代码页的子集),并且不需要手动迭代字节。将这些点加在一起,简化的变体如下所示:
try(FileChannel fileChannel = FileChannel.open(
Paths.get("resources\\MappedByteBufferExample.txt"),
StandardOpenOption.READ, StandardOpenOption.WRITE)) {
long size = fileChannel.size();
MappedByteBuffer mappedBuffer = fileChannel.map(MapMode.READ_WRITE, 0, size);
System.out.println("Text from File : -----");
System.out.append(Charset.defaultCharset().decode(mappedBuffer)).println("\n");
for(int index1 = 0, index2=(int)size-1; index1<index2; index1++, index2--) {
byte b1 = mappedBuffer.get(index1), b2 = mappedBuffer.get(index2);
mappedBuffer.put(index1, b2).put(index2, b1);
}
mappedBuffer.force();
mappedBuffer.flip();
System.out.println("Text Reversed : -----");
System.out.append(Charset.defaultCharset().decode(mappedBuffer)).println("\n");
} catch (IOException e) {
e.printStackTrace();
}请记住,无论是否将其写入文件,读取循环都将始终显示已更改的状态。因此,force()是放在读取循环之前还是放在块的末尾并不重要。
https://stackoverflow.com/questions/39817028
复制相似问题