/** * FileInputDemo opens a file specified as a command-line * argument, reads the file line by line, and prints an * upper-case version of the file to standard output. * * @author Jeff Ondich, 1/14/04 */ import java.io.*; public class FileInputDemo { public static void main( String[] args ) { // It's good to tell people when they are invoking the program incorrectly. if( args.length < 1 ) { System.out.println( "Usage: java FileInputDemo someFileName" ); System.exit( 1 ); } // You need to declare and initialize the BufferedReader out here // so it will still be in scope after the try/catch blocks. BufferedReader in = null; try { in = new BufferedReader( new FileReader( args[0] ) ); } catch( FileNotFoundException e ) { System.out.println( "Can't open " + args[0] + " for reading." ); System.out.println( "Perhaps you didn't spell the file name correctly." ); System.exit( 1 ); } // If we get here, the file is open and ready to read. // We'll read it by using an intentional infinite loop and // a "break" statement when reading fails. while( true ) { String line = null; try { line = in.readLine(); } catch( IOException e ) { System.out.println( "Something sad occurred while reading the file. I give up." ); System.exit( 1 ); } if( line == null ) break; System.out.println( line.toUpperCase() ); } // It's good to close files when you're done with them. It // frees up memory and other operating system resources. try { in.close(); } catch( IOException e ) { System.out.println( "BufferedReader.close failed. Weird." ); System.exit( 1 ); } } }