Constructing a PrintStream on a File
To write to a file, construct a PrintStream over a File and then use the same println / print / printf methods you have used on System.out.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
public static void writeReport(final String filename) throws FileNotFoundException {
final PrintStream out = new PrintStream(new File(filename));
out.println("Report");
out.println("------");
out.printf("Pi: %.4f%n", Math.PI);
out.close(); // flush + release the OS file handle
}
Four things to know about this constructor:
1. It creates the file if it does not exist. Unlike the read side (where a missing file causes FileNotFoundException), the write side's FileNotFoundException only fires when the path is invalid: typically because a directory in the path does not exist, or the program lacks permission to write there. A missing leaf file is created.
2. It overwrites any existing file with the same name. Opening for write truncates the file to length zero before any data is written. If you wanted to append instead, you would need the (File, String) or (File, Charset) overload with append=true, but the simple constructor truncates.
3. It is declared to throw FileNotFoundException (same as the Scanner(File) constructor on the read side). The handle-or-declare rule (JLS §11.2) applies; every method that constructs a PrintStream(File) must declare or catch.
4. Buffering means close() is mandatory. PrintStream buffers output internally. Bytes you "printed" may still be in the buffer when the program exits, and if the JVM crashes before close() runs, those bytes are lost. Calling close() flushes the buffer to disk and releases the OS file handle. Forgetting to close is the classic "my file is empty even though I printed to it" bug.
When the directory does not exist
new PrintStream(new File("missing-dir/out.txt")) throws FileNotFoundException with the message "missing-dir/out.txt (No such file or directory)". The constructor does not create parent directories. Pre-flight by checking the parent exists, or use f.getParentFile().mkdirs() if creating the tree is acceptable.
In other languages
- Python:
open(filename, "w")truncates;open(filename, "a")appends. Use awithblock to auto-close. - C:
fopen(filename, "w")truncates;fopen(filename, "a")appends.fcloseis mandatory. - Bash:
> file.txttruncates;>> file.txtappends.