gpt4 book ai didi

java - 追加一个文件,而不是覆盖它?

转载 作者:行者123 更新时间:2023-11-29 07:51:50 25 4
gpt4 key购买 nike

我写入文本文件的代码现在看起来像这样:

 public void resultsToFile(String name){
try{
File file = new File(name + ".txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Titel: " + name + "\n\n");
for(int i = 0; i < nProcess; i++){
bw.write("Proces " + (i) + ":\n");
bw.write("cycles needed for completion\t: \t" + proc_cycle_instr[i][0] + "\n");
bw.write("instructions completed\t\t: \t" + proc_cycle_instr[i][1] + "\n");
bw.write("CPI: \t" + (proc_cycle_instr[i][0]/proc_cycle_instr[i][1]) + "\n");
}
bw.write("\n\ntotal Cycles: "+totalCycles);
bw.close();
}catch(IOException e){
e.printStackTrace();
}
}

但是,这会覆盖我以前的文本文件,而我希望将它附加到已经存在的文件中!我做错了什么?

最佳答案

FileWriter fw = new FileWriter(file.getAbsoluteFile() ,true);

通过传递 append true 以追加模式打开。

   public FileWriter(File file, boolean append)    throws IOException

Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

关于java - 追加一个文件,而不是覆盖它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20583123/

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