Don
Don

Reputation: 1458

Appending a file, instead of overwriting it?

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?

Upvotes: 1

Views: 159

Answers (3)

A N M Bazlur Rahman
A N M Bazlur Rahman

Reputation: 2300

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
     */

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 122026

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.

Upvotes: 4

Ren&#233; Link
Ren&#233; Link

Reputation: 51473

Use

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

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

Upvotes: 1

Related Questions