Appending to a File
How to add lines to the end of a file by opening a `FileOutputStream` in append mode.
Journeyman · Java · Updated
If you need to append new information to a file you can create a file stream with the append setting set to true. To do this you have to create the FileOutputStream object manually, and then create the PrintWriter.
var student = new Student("Zoe","Whitehouse",3.95);
var file = new File("student_grades.csv");
// the second argument specifies that you want to append
try(var stream = new FileOutputStream(file, true);
var writer = new PrintWriter(stream))
{
writer.printf("%s,%s,%.2f\n"
, student.getFirstName()
, student.getLastName()
, student.getGpa());
}
catch(IOException ex)
{
System.out.println(ex.getMessage());
}
Do it: replace or append
A new student joins the class, and the grade book writes their line to the class file. What's in the file afterwards depends on how the file was opened: new PrintWriter(file) replaces the file, and a FileOutputStream opened with true adds to its end.
The box has no files, so a file's lines are a List<String> here. Your method works out what the file holds after the new lines are written, either way.
The method gets three values:
fileLines: the lines the file holds now. An empty list is a file that doesn't exist yet.newLines: the lines being written.append:trueto add to the end of the file,falseto replace it.
For example, the class file and one new student:
List<String> fileLines = List.of("firstname,lastname,gpa", "Emily,Wilson,3.91");
List<String> newLines = List.of("Zoe,Whitehouse,3.95");
append |
The file afterwards |
|---|---|
true |
firstname,lastname,gpa, Emily,Wilson,3.91, Zoe,Whitehouse,3.95 |
false |
Zoe,Whitehouse,3.95 |
So afterWriting(fileLines, newLines, true) returns a list of those three lines, in that order.
Your job: write the method afterWriting(List<String> fileLines, List<String> newLines, boolean append) so it returns a new List<String>: the file's lines after writing.
- When
appendistrue: the lines already there, in order, then the new lines. - When
appendisfalse: only the new lines. Whatever was there is gone. - Build a new list; don't change
fileLinesornewLines. - Appending to a file that doesn't exist yet (an empty
fileLines) gives only the new lines, as Java creates the file.
Practiced live on the lesson page: write the Java right there and check it.