img
To write to the console by using a PrintWriter, specify System.out for the output stream
and flush the stream after each newline. For example, this line of code creates a PrintWriter
that is connected to console output:
PrintWriter pw = new PrintWriter(System.out, true);
The following application illustrates using a PrintWriter to handle console output:
// Demonstrate PrintWriter
import java.io.*;
public class PrintWriterDemo {
public static void main(String args[]) {
PrintWriter pw = new PrintWriter(System.out, true);
pw.println("This is a string");
int i = -7;
pw.println(i);
double d = 4.5e-7;
pw.println(d);
}
}
The output from this program is shown here:
This is a string
-7
4.5E-7
Remember, there is nothing wrong with using System.out to write simple text output
to the console when you are learning Java or debugging your programs. However, using a
PrintWriter will make your real-world applications easier to internationalize. Because
no advantage is gained by using a PrintWriter in the sample programs shown in this topic,
we will continue to use System.out to write to the console.
Reading and Writing Files
Java provides a number of classes and methods that allow you to read and write files. In Java,
all files are byte-oriented, and Java provides methods to read and write bytes from and to a
file. However, Java allows you to wrap a byte-oriented file stream within a character-based
object. This technique is described in Part II. This chapter examines the basics of file I/O.
Two of the most often-used stream classes are FileInputStream and FileOutputStream,
which create byte streams linked to files. To open a file, you simply create an object of one of
these classes, specifying the name of the file as an argument to the constructor. While both
classes support additional, overridden constructors, the following are the forms that we will
be using:
FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home