Java Reference
In-Depth Information
figure 2.19
Program to list
contents of a file
1
import java.util.Scanner;
2
import java.io.FileReader;
3
import java.io.IOException;
4
5
public class ListFiles
6
{
7
public static void main( String [ ] args )
8
{
9
if( args.length == 0 )
10
System.out.println( "No files specified" );
11
for( String fileName : args )
12
listFile( fileName );
13
}
14
15
public static void listFile( String fileName )
16
{
17
Scanner fileIn = null;
18
19
System.out.println( "FILE: " + fileName );
20
try
21
{
22
fileIn = new Scanner( new FileReader( fileName ) );
23
while( fileIn.hasNextLine( ) )
24
{
25
String oneLine = fileIn.nextLine( );
26
System.out.println( oneLine );
27
}
28
}
29
catch( IOException e )
30
{ System.out.println( e ); }
31
finally
32
{
33
// Close the stream
34
if( fileIn != null )
35
fileIn.close( );
36
}
37
}
38
}
listFile
, we construct the
FileReader
object at line 22, and then use it to
construct a
Scanner
object,
fileIn
. At that point, reading is identical to what
we have already seen.
After we are done with the file, we must close it; otherwise, we could
eventually run out of streams. Note that this cannot be done at the end of the
try
block, since an exception could cause a premature exit from the block.
Thus we close the file in a
finally
block, which is guaranteed to be started
Search WWH ::
Custom Search