gpt4 book ai didi

java - 为什么 FileWriter 会覆盖文件,即使我确实指定它应该附加

转载 作者:行者123 更新时间:2023-12-01 22:10:06 25 4
gpt4 key购买 nike

这就是我所拥有的:

try{
String filename = "Names.txt";
FileWriter fw = new FileWriter(filename, true);
BufferedWriter buffer = new BufferedWriter(fw);
buffer.append("NAME: " + name + " AGE: " + age + " ID: " + id + "\n\n");

System.out.println("We have succefully created your account.");
buffer.close();
start();
} catch(IOException e){
System.err.println("ERROR");
}

它总是覆盖第一行并且不会转到不同的行。我已经使用了附加。这是我的启动方法:

// this is the start method
public static void start(){
System.out.println("1) Add Account 2) Exit");
System.out.println("What do you want to do: ");
stuff = input.nextInt();

if (stuff == 1) {
try {
x = new Formatter("Names.txt");
} catch (Exception e) {
System.err.println("ERROR" );
}
newRecord();
} else if(stuff == 2) {
System.exit(0);
} else {
System.err.println("ERROR");
}
}

最佳答案

我猜是这一行:

x = new Formatter("Names.txt");

来自javadoc

public Formatter(String fileName) throws FileNotFoundException

Parameters:

fileName - The name of the file to use as the destination of this formatter. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.

(我强调了清理文件的部分)。

关于java - 为什么 FileWriter 会覆盖文件,即使我确实指定它应该附加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31954212/

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