gpt4 book ai didi

java - 如何写入/读取文本文件的开头?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:54:01 25 4
gpt4 key购买 nike

编辑这是我的文件阅读器,我能不能让它从下往上读,看看让它从下往上写有多难。

        BufferedReader mainChat = new BufferedReader(new FileReader("./messages/messages.txt"));
String str;
while ((str = mainChat.readLine()) != null)
{
System.out.println(str);
}
mainChat.close();

或(旧问题)

我怎样才能让它把下一个字符串放在文件的开头,然后插入一个新行(将其他行向下移动)?

FileWriter chatBuffer = new FileWriter("./messages/messages.txt",true);
BufferedWriter mainChat = new BufferedWriter(chatBuffer);
mainChat.write(message);
mainChat.newLine();
mainChat.flush();
mainChat.close();

最佳答案

有人可以纠正我,但我很确定在大多数操作系统中,除了读入整个文件,然后再写回之外别无选择。

我想主要原因是,在大多数现代操作系统中,光盘上的所有文件都从边界的开头开始。问题是,你不能告诉文件分配表你的文件比那个点早开始。

因此,文件中所有后面的字节都必须重写。我不知道有任何操作系统例程可以一步完成这一任务。

因此,我会使用 BufferedReader 将整个文件存储到 VectorStringBuffer 中,然后用前置字符串将其全部写回首先。

--

编辑

阅读@Saury 的 randomaccessfile 建议,一种可以为较大文件节省内存的方法是:

file has N bytes to start with
we want to add on "hello world"
open the file for append
append 11 spaces
i=N
loop {
go back to byte i
read a byte
move to byte i+11
write that byte back
i--
} until i==0
then move to byte 0
write "hello world"

关于java - 如何写入/读取文本文件的开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7801482/

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