1

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-
  • 218,210
  • 55
  • 464
  • 476

2 Answers2

4

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
  • 283,665
  • 25
  • 256
  • 373
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
  • 595
  • 1
  • 9
  • 22