gpt4 book ai didi

java - MappedByteBuffer 写入文件不起作用

转载 作者:行者123 更新时间:2023-12-01 21:17:18 25 4
gpt4 key购买 nike

我很难理解 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时代sesoR

但是文件的内容没有改变。第二次执行该程序时,控制台的输出为:

文件中的文本:-----

!deR时代sesoR

文本反转:-----

玫瑰是红色的!

文件内容仍然没有改变。我一次尝试了一个 load() 和 force() 方法,但结果没有变化这是我的问题:

1)为什么本地文件的内容没有改变?

2)该程序需要进行哪些更改才能将数据写入文件?

3) 尽管文件内容未反转,但 MappedByteBuffer 为什么/如何在第二次迭代中读取反转文本?

最佳答案

文件内容已更改。普通编辑器(如 notepad++ 或 eclipse)不会注释更改,因为使用 RandomAccessFile 不会更改文件日期时间。但如果您确实在运行后手动重新加载文件,您应该会看到更改。

关于java - MappedByteBuffer 写入文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39817028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com