The PrintWriter Stream in Java

The PrintWriter stream is used for printing strings and numbers in text format. A PrintWriter stream can be wrapped around any byte OutputStream or character Writer stream, including FileWriter. The PrintWriter class implements all the print methods of the PrintStream class. The WritePrintFile program has the same functionality as the WriteFile program from Section 7.2.1, but outputs to a PrintWriter wrapped around a FileWriter stream.

WritePrintFile

import java.io.*;

public class WritePrintFile
{

public static void main(String[] args) throws
IOException
{
String text;
int i;

File outputFile = new File("File1.txt");
FileWriter out = new FileWriter(outputFile);
PrintWriter p = new PrintWriter(out);
for (i=1; i<11; i++) {
p.println("Line " + i + " of text");
}
p.close();
out.close();
}
}




In lines 10–12, we create a PrintWriter object, p, wrapped around the FileWriter stream, out, which outputs to our file File1.txt. Note in line 14, we use the PrintWriter println method, which prints the string then terminates the line, so dispensing with the \n newline character.

No comments:

Post a Comment