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

标签 java file

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

 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/

相关文章:

java - 当我在 Reducer 中读取它们时,Mapper 中发送的文本/字符串值是错误的

java - 使用 Spring 和外部消息代理进行消息传递

java - 这些 "if statements"可以简化吗?

c - 在c中打开文件并打印到文件

javascript - Selenium:在 Firefox 中启用 XPCOM 访问并从 Javascript 写入文件

java - 文档附件的 anchor 链接

java - 如何使用BroadcastReceiver删除传入的短信?

c - 在C中覆盖文本文件

python - 为什么使用 int() 内置从 .txt 文件读取部分行时抛出 ValueError ?

file - UWP : Catch error when reading file