Task 3 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

(Optional) 6.4 Writing files — writing to a file

Lesson

Optional lesson — beyond the AP CS A exam. Writing to files is not on the AP exam (which only reads files); this is here for a fuller picture of Java.

Writing to a text file

To write to a file, create a PrintWriter from a File (or file name), write with print/println, and always close() when done — closing flushes and saves the file. Opening a file for writing can fail, so the method declares throws IOException.


Worked example

public static void writeGreeting(String fileName) throws IOException {
    PrintWriter out = new PrintWriter(new File(fileName));
    out.println("Hello!");
    out.println("Goodbye.");
    out.close();   // flush and save
}

Create the writer on the file, write the lines, and close. (Imports like java.io.PrintWriter, java.io.File, and java.io.IOException are provided.)


▶ Try it: the example below writes to the screen; swap System.out for a file and the same println calls write to that file.



To write to a file, you create a PrintWriter from a...


Why call close() after writing to a file?


Type exactly what this program prints.

String[] n = {"Ada", "Sam"};
int[] s = {88, 91};
PrintWriter out = new PrintWriter(System.out);
for (int i = 0; i < n.length; i++) {
    out.println(n[i] + ": " + s[i]);
}
out.flush();

Because opening a file for writing can fail, the method header includes...


True or false?