Prev | Current Page 230 | Next

Carl Reynolds and Paul Tymann

"Schaum's Outline of Principles of Computer Science"

Without the BufferedReader, a
FileReader only has methods to read characters.
Here is a little program to read a file of character data and display it on the screen:
import java.io.*;
/**
* A program that opens a character based file,
* specified on the command line,
* and shows its contents on standard output.
*
* @author Carl Reynolds
*/
public class ShowFile {
public static void main( String args[] ) {
BufferedReader in = null;
String line;
// Make sure the number of arguments is correct
if ( args.length != 1) {
System.err.println( "Usage: ShowFile sourceFile" );
System.exit(1);
}
// Attempt to open the file for reading
try {
in = new BufferedReader( new FileReader( args[0] ) );
}
catch ( FileNotFoundException e ) {
System.err.println( "ShowFile: " + e.getMessage() );
System.exit( 1 );
}
// Read and display
try {
while ( (line = in.readLine() ) != null ) {
System.out.println( line );
}
}
catch ( IOException e ) {
System.err.println( "ShowFile: " + e.getMessage() );
System.exit( 1 );
}
finally {
// Close the file
try{
in.close();
}
catch( Exception e ) {}
}
}//main
} //ShowFile
CHAP. 5] PROGRAMMING IN JAVA 89
This program checks the command line arguments in the array of Strings called args to make sure that the
user provided a parameter for the file name.


Pages:
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
pustaki szklane House Extension Kąty Rybackie noclegi kasyno Kołobrzeg