PrintWriter Class
Package: java.io
The PrintWriter
class lets you write data to an output stream. Although you can connect a PrintWriter
to any object that implements Writer
, you’ll use it most often in conjunction with a BufferedWriter
object.
Constructors
Constructor |
Description |
|
Creates a print writer for the specified output writer. |
|
Creates a print writer for the specified output writer. If the second parameter is |
Methods
Method |
Description |
|
Closes the file. |
|
Writes the contents of the buffer to the hard drive. |
|
Writes the value, which can be any primitive type or any object. If the value is an object, the object’s |
|
Writes the value, which can be any primitive type or any object. If the value is an object, the object’s |
Creating a PrintWriter object
Creating a PrintWriter
object to write data to an output file is a bit of a convoluted process that typically involves four distinct classes. First, you must create a File
object, which identifies the output file. Then you create a FileWriter
to write to the file. But because the FileWriter
is inefficient, you next create a BufferedWriter
for more efficient output. Only then can you create a PrintWriter
. Here’s the resulting code:
File file;
FileWriter fwriter;
BufferedWriter bwriter;
PrintWriter out;
file = new File(“myfile.txt”);
fwriter = new FileWriter(file);
bwriter = new BufferedWriter(fwriter);
out = new PrintWriter(bwriter);
Writing to a character stream
To write data to a file connected to a PrintWriter
, you use the print
and println
methods.
System.out.print(firstname;
System.out.print(“ ”);
System.out.println(lastname);
Here, a variable named firstname
is written to the file, followed by a Tab character, followed by a variable named lastname
. The lastname
variable is written with the println
method rather than the print
method. That ends the current line.
If you prefer to be a little more efficient, you can build a string representing the entire line and then write the line all at once, as follows:
String line = firstname + “ ” + lastname;
System.out.println(line);
out.flush();
Also, when you’re finished writing data to the file, you can close the file by calling the close
method, like this:
out.close();