0

Everytime I re-ask the user to enter their grades, I have it write a string to the file gradeReport, but everytime the while loop repeats, the previous result is erased. HOw do I get several lines outputted in the file?

//Open file and call writeToFile method        
         PrintWriter outputFile= new PrintWriter("gradeReport.txt");
         outputFile.println(s.writeToFile());
         outputFile.close();

And the method:

public String writeToFile() 
    { 
     DecimalFormat f = new DecimalFormat("0.00");
        String str= name + "--" + id + "--" + f.format(getPercentage())+ "--" + getGrade();
      return str;
    }
Ry-
  • 209,133
  • 54
  • 439
  • 449

2 Answers2

3

Wrap the PrintWriter around a FileWriter that is set to append to the file.

PrintWriter outputFile= new PrintWriter(new FileWriter("gradeReport.txt", true));
  • Note 1: the FileWriter constructor's second parameter of true means that it is set to append to the file rather than to over-write the file.
  • Note 2: this question will likely and appropriately be closed soon as a duplicate.
Hovercraft Full Of Eels
  • 280,125
  • 25
  • 247
  • 360
2

Try using the constructor FileWriter(String filename, boolean append) to open the file in append mode.

FileWriter fw = new FileWriter("filename.txt", true);
H3XXX
  • 594
  • 1
  • 9
  • 20