1

My code for writing to a text file now looks like this:

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

However, This overwrites my previous text files, whilst instead I want it to be appended to the already existing file! What am I doing wrong?

Don
  • 1,428
  • 3
  • 15
  • 31
  • 1
    possible duplicate of [Trouble with filewriter overwriting files instead of appending to the end](http://stackoverflow.com/questions/10804286/trouble-with-filewriter-overwriting-files-instead-of-appending-to-the-end) – Raedwald Dec 14 '13 at 12:16

3 Answers3

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

Open in append mode by passing 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.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
1

Use

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

to append to the file and take a look the javadoc of FileWriter(String, boolean)

René Link
  • 48,224
  • 13
  • 108
  • 140
0
public FileWriter(File file, boolean append) throws IOException {
}

use this method:

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
     */
A N M Bazlur Rahman
  • 2,280
  • 6
  • 38
  • 51