附加文件,而不是覆盖它?

时间:2013-12-14 12:12:02

标签: 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();
    }
}

但是,这会覆盖我之前的文本文件,而我希望将它附加到现有文件中!我做错了什么?

3 个答案:

答案 0 :(得分:4)

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

通过传递append true在附加模式中打开。

   public FileWriter(File file, boolean append)    throws IOException
  给定File对象的

Constructs a FileWriter对象。如果第二个参数为true,则字节将写入文件的末尾而不是开头。

答案 1 :(得分:1)

使用

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

附加到文件并查看FileWriter(String, boolean)

的javadoc

答案 2 :(得分:0)

public FileWriter(File file, boolean append) throws IOException {
}

使用此方法:

JavaDoc:

/**
     * Constructs a FileWriter object given a File object. If the second
     * argument is <code>true</code>, then bytes will be written to the end
     * of the file rather than the beginning.
     *
     * @param file  a File object to write to
     * @param     append    if <code>true</code>, then bytes will be written
     *                      to the end of the file rather than the beginning
     * @throws IOException  if the file exists but is a directory rather than
     *                  a regular file, does not exist but cannot be created,
     *                  or cannot be opened for any other reason
     * @since 1.4
     */
相关问题