-1

I am trying to write missed responses to an external text file. The below method stored responses not recognized into an external text file, but overwrites the previous content. How do I stop it from overwriting?

//The write a list method

       public void writeAList(ArrayList<String> list, String filename)
        {
            if(list != null) {
                try (FileWriter writer = new FileWriter(filename)) {
                    for(String item : list) {
                        writer.write(item.trim());
                        writer.write('\n');
                    }                    
                }
                catch(IOException e) {
                    System.out.println("Problem writing file: " + filename +
                                       " in writeAList");
                }
            }
            else {
                System.out.println("Null list passed to writeAList.");
            }
        }

//I am calling it in this method

public String generateResponse(ArrayList<String> words)
{
    Iterator<String> it = words.iterator();
    while(it.hasNext()) {
        String word = it.next();
        String response = responseMap.get(word);
        if(response != null) {
            return response;
        }
    }
    //If we get here, none of the words from the input line was recognized
    //In this case, a default response is returned
    //The words not recognised are stored in "missed.txt"
    helper.writeAList(words,"missed.txt");
    return pickDefaultResponse();

}
mr K
  • 25
  • 4
  • 2
    This might help: http://stackoverflow.com/questions/1225146/java-filewriter-with-append-mode – Atri Nov 26 '15 at 20:15

2 Answers2

1

Instead of new FileWriter(filename)

try

new FileWriter(filename, true)

Which creates the file writer in append mode, see the docs here

Egg Vans
  • 944
  • 10
  • 21
0

In your code, you need to replace:

FileWriter writer = new FileWriter(filename)

With:

FileWriter writer = new FileWriter(filename, true)

Where the extra parameter true is to enable the append mode.

Atri
  • 5,511
  • 5
  • 30
  • 40
  • perfect thank you, one more question, how do I make the responses go on a new line? currently it just writes everything as one line? – mr K Nov 26 '15 at 20:19
  • @ashutosh It looks like you are adding a new line ok , so it may just be the editor you are using to look at the file not showing \n as a new line try changing \n to \r\n – Egg Vans Nov 26 '15 at 20:27