Java Reference
In-Depth Information
5
System.out.println("This program produces four");
6
System.out.println("lines of output.");
7
}
8}
Here is a variation that sends its output to a file called hello.txt :
1 // Variation of Hello2 that prints to a file.
2
3 import java.io.*;
4
5 public class Hello4 {
6
public static void main(String[] args)
7
throws FileNotFoundException {
8
PrintStream output =
9
new PrintStream( new File("hello.txt"));
10
output.println("Hello world.");
11
output.println();
12
output.println("This program produces four");
13
output.println("lines of output.");
14
}
15 }
When you run this new version of the program, a curious thing happens. The pro-
gram doesn't seem to do anything; no output appears on the console at all. You're so
used to writing programs that send their output to the console that this might seem
confusing at first. We don't see any output in the console window when we run this
program because the output was directed to a file instead. After the program finishes
executing, you can open up the file called hello.txt and you'll find that it contains
the following:
Hello world.
This program produces four
lines of output.
The main point is that everything you've learned to do with System.out , you can
also do with PrintStream objects that are tied to files.
You can also write methods that take PrintStream objects as parameters. For
example, consider the task of fixing the spacing for a series of words. Say that you
have a line of text with erratic spacing, like the following line:
a new nation, conceived in liberty
 
Search WWH ::




Custom Search