FileStream Defaults
Writing to a file with a `PrintWriter`, which by default replaces the file or creates a new one.
Journeyman · Java · Updated
When we read from files we use a Scanner. When we write to files we use a PrintWriter, because it makes writing to a file feel like writing to the console.
When you create a PrintWriter from a File, Java creates a FileOutputStream with default settings for you.
Assume you have a collection of students with their names and grades, and you want to save the information to a file. We will open a writable file stream. If a file with the specified name already exists, it will be overwritten. If a file does not exist, a new one will be created.
File file = new File("student_grades.csv");
try(PrintWriter writer = new PrintWriter(file))
{
// write the header line
writer.println("firstname,lastname,gpa");
students.forEach(student -> {
writer.printf("%s,%s,%.2f\n"
, student.getFirstName()
, student.getLastName()
, student.getGpa());
});
}
catch(IOException ex)
{
System.out.println(ex.getMessage());
}
Do it: build the honor roll's lines
The grade book saves the honor roll as a CSV file. Opening the file is the PrintWriter's job; the real work is building each line it writes. The box has no files, so your method returns the lines, in the order the PrintWriter would write them.
String.format takes the same pattern as printf, and gives back the text instead of writing it: String.format("%s,%s,%.2f", "John", "Smith", 2.5) gives "John,Smith,2.50". %s puts in a string, and %.2f a number with two decimal places.
Student is given at the bottom of the file, with getFirstName(), getLastName() and getGpa().
The method gets one value:
students: the students to save, aList<Student>.
For example:
List<Student> students = List.of(new Student("Emily", "Wilson", 3.91), new Student("John", "Smith", 2.5));
| Line | Comes from |
|---|---|
firstname,lastname,gpa |
The header, always first |
Emily,Wilson,3.91 |
Emily Wilson, 3.91 |
John,Smith,2.50 |
John Smith, 2.5, written with two decimal places |
So csvLines(students) returns a list of those three lines, in that order.
Your job: write the method csvLines(List<Student> students) so it returns a List<String>.
- The first line is the header,
firstname,lastname,gpa. - Then one line for each student, in the list's order: the first name, the last name and the GPA, separated by commas, with no spaces.
- Write each GPA with exactly two decimal places:
2.5becomes2.50, and3.456becomes3.46. - With no students, the list holds only the header.
Practiced live on the lesson page: write the Java right there and check it.