使用RandomAccessFile在中间插入文本后会删除一些文本 [英] Inserting text in middle using RandomAccessFile removes some text after that
问题描述
我的示例代码
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
demo.txt before execution
one two three
Text to be appended with
five six seven
eight nine ten
执行后的demo.txt
demo.txt after execution
one two three
Text to be appended with
new text has been appendedten
此外我尝试使用setLength更改长度附加新文本之前的文件但是仍有一些文本正在从输出文件中删除。任何帮助将不胜感激
Also i tried using setLength to change length of file before new text is appended. But still some text is getting trimmed from output file. Any help will be appreciated
谢谢
Mathew
Thanks Mathew
推荐答案
随机访问文件的行为类似于存储在
文件系统中的大量字节。
A random access file behaves like a large array of bytes stored in the file system.
实际上它并不关心在写操作的情况下移位数组元素(只有指针很先进)。这样的操作会覆盖现有值:
In fact it does not care about shifting the array elements in the case of write operations (only the pointer is advanced). Such an operation overwrites existing values:
输出操作从文件指针开始写入字节,并使文件指针超过字节前进
写的。
Output operations write bytes starting at the file pointer and advance the file pointer past the bytes written.
这篇关于使用RandomAccessFile在中间插入文本后会删除一些文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!