Java Reference
In-Depth Information
The following program puts these concepts to work. It reads all lines of an input file
and sends them to the output file, preceded by line numbers. If the input file is
Mary had a little lamb
Whose fleece was white as snow.
And everywhere that Mary went,
The lamb was sure to go!
then the program produces the output file
/* 1 */ Mary had a little lamb
/* 2 */ Whose fleece was white as snow.
/* 3 */ And everywhere that Mary went,
/* 4 */ The lamb was sure to go!
The line numbers are enclosed in /* */ delimiters so that the program can be used for
numbering Java source files.
There one additional issue that we need to tackle. When the input or output file
doesn't exist, a
FileNotFoundException
can occur. The compiler insists that
we tell it what the program should do when that happens. (In this regard, the
FileNot-FoundException
is different from the exceptions that you have
already encountered. We will discuss this difference in detail in
Section 11.3
.) In our
sample program, we take the easy way out and acknowledge that the
main
method
should simply be terminated if the exception occurs. We label the
main
method like
this:
public static void main(String[] args)
throws
FileNotFoundException
You will see in the following sections how to deal with exceptions in a more
professional way.
ch11/fileio/LineNumberer.java
1
import
java.io.FileReader;
2
import
java.io.FileNotFoundException;
3
import
java.io.PrintWriter;
4
import
java.util.Scanner;
5
6
public class
LineNumberer
7 {