-1

Sorry for the confusing title. I tried to make it as concise as possible. I am reading from an input file, parsing it, and writing to an output file. The problem I am having is once the program finishes running, the output file only contains the last item that is read from the input. Each input is being overwritten by the next. I think my problem lies in this code segment.

 protected void processLine(String aLine) throws IOException {
   Scanner scanner = new Scanner(aLine);
   scanner.useDelimiter(" ");

   if (scanner.hasNext()){
     String input = scanner.next();

     PrintWriter writer = new PrintWriter(new FileWriter("output.txt"));
     writer.println(input);
     writer.close();     
    } else {
        System.out.println("Empty or invalid line. Unable to process.");
      }
   }

Any and all help/advice is appreciated.

Shrp91
  • 173
  • 2
  • 5
  • 14

2 Answers2

2

Just add true as a parameter to open the file in append mode

 PrintWriter writer = new PrintWriter(new FileWriter("output.txt",true));

Append mode makes sure that while adding new content, the older content is retained. Refer the Javadoc

Ankit Rustagi
  • 5,539
  • 12
  • 39
  • 70
  • +1. I've always wondered if this was possible, but never really looked into it. I didn't realize it was as simple as adding a `,true` into my code. – Justin Nov 15 '13 at 23:15
  • Use the new [javadoc](http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter%28java.io.File,%20boolean%29) – Justin Nov 15 '13 at 23:31
0

You could open the file in append mode, but it would be better not to open and close the output file every time around the loop. Open it once before you start, and close it when finished. This will be far more efficient.

user207421
  • 305,947
  • 44
  • 307
  • 483