gpt4 book ai didi

java - 将文本附加到现有文件而不覆盖它

转载 作者:行者123 更新时间:2023-12-01 11:49:28 26 4
gpt4 key购买 nike

我正在向现有文件添加一些内容 NameList.txt ,其中已经包含一些文本。

但是当我运行该程序时,它会在开始编写新内容之前删除所有现有内容。

注意:我还尝试查找文件结束行在哪里。例如。通过使用while ((lines = reader.readLine()) == null) ,其中lines变量的类型为String .

public class AddBooks {

public static void main(String[] args) {

Path Source = Paths.get("NameList.txt");

Charset charset = Charset.forName("Us-ASCII");
try (
BufferedWriter write = Files.newBufferedWriter(Source, charset);
BufferedReader reader = Files.newBufferedReader(Source, charset);
) {
Scanner input = new Scanner(System.in);
String s;
String line;
int i = 0, isEndOfLine;

do {
System.out.println("Book Code");
s = input.nextLine();
write.append(s, 0, s.length());
write.append("\t \t");

System.out.println("Book Title");
s = input.nextLine();
write.append(s, 0, s.length());
write.append("\t \t");

System.out.println("Book Publisher");
s = input.nextLine();
write.append(s, 0, s.length());
write.newLine();

System.out.println("Enter more Books? y/n");
s = input.nextLine();

} while(s.equalsIgnoreCase("y"));
} catch (Exception e) {
// TODO: handle exception
}
}
}

我唯一的要求是向现有文件添加新内容。

最佳答案

像这样改变你的代码!

BufferedWriter write = Files.newBufferedWriter(Source, charset, StandardOpenOption.APPEND);

看看这个! StandardOpenOption

第二..

 while ((str = in.readLine()) != null)

附录..插入

writer.close();

之前

} while(s.equalsIgnoreCase("y"));

关于java - 将文本附加到现有文件而不覆盖它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28911016/

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