gpt4 book ai didi

java - 使用 RandomAccessFile 在中间插入文本会删除一些文本

转载 作者:行者123 更新时间:2023-12-04 00:32:54 24 4
gpt4 key购买 nike

我的示例代码

    String line = null;
RandomAccessFile file = new RandomAccessFile("D:/mahtew.txt", "rw");
System.out.println(file.getFilePointer());
while((line = file.readLine()) != null){
System.out.println(line);
System.out.println(file.getFilePointer());

if(line.contains("Text to be appended with")){
file.seek(file.getFilePointer());
file.write(" new text has been appended".getBytes());
break;
}
}
file.close();

执行前的demo.txt

one two three
Text to be appended with
five six seven
eight nine ten

执行后的demo.txt

one two three
Text to be appended with
new text has been appendedten

我还尝试在附加新文本之前使用 setLength 更改文件长度。但是仍然有一些文本从输出文件中被删除。任何帮助将不胜感激

谢谢马修

最佳答案

RandomAccessFile

A random access file behaves like a large array of bytes stored in the file system.

实际上它并不关心在写操作的情况下移动数组元素(只有指针是先进的)。这样的操作会覆盖现有值:

Output operations write bytes starting at the file pointer and advance the file pointer past the bytes written.

关于java - 使用 RandomAccessFile 在中间插入文本会删除一些文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15461555/

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