PrintWriter Class
layout: default
title: PrintStream and PrintWriter
You've been using PrintStream since your first "Hello, World" program: System.out and System.err are PrintStream objects.
PrintStream provides print, println, and printf, as well as methods for writing bytes and byte arrays.
PrintWriter has all the same methods as PrintStream.
- A
PrintWritercan also writechararrays instead ofbytearrays.
You can construct a PrintStream using a File, an OutputStream, or a filename.
try {
FileOutputStream fs = new FileOutputStream("test.txt");
PrintStream ps = new PrintStream(fs);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
PrintWriter using a File, an OutputStream, a filename, or another Writer object.
FileWriter fw = new FileWriter("test.txt");
PrintWriter pw = new PrintWriter(fw);
Practice Exercise¶
PrintStreamwas one of the first I/O classes in Java. When writers were later added tojava.ioto handle character output,PrintWriterwas created as a replacement forPrintStream. However,System.outandSystem.errwere already in wide use so they remainPrintStreams. You will usually usePrintWriterin your own code.
The various output methods don't throw IOException, though constructors might.
String[] data = { "Cat", "Dog", "Frog", "Giraffe" };
try {
FileWriter fw = new FileWriter("test.txt");
PrintWriter pw = new PrintWriter(fw);
for (String string : data) {
pw.println(string);
}
pw.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
Practice Exercise¶
Output does not have to go to a file. The
java.iopackage has classes allowing you to use these I/O methods to read and write data in aStringbuffer in memory, or as data streamed between two Java objects in different threads of an application, among other possibilities. We'll stick with text files here though.