// Copy input file to output file, with line numbering. // If no output file, use standard output. import java.io.*; public class NumberLines { public static void main( String [ ] args ) { PrintWriter fileOut = null; BufferedReader fileIn = null; try { if( args.length == 1 ) fileOut = new PrintWriter( System.out ); else if ( args.length == 0 || args.length > 2 ) { System.out.println( "Usage: java NumberLines sourceFile destFile" ); return; } else if ( args[ 0 ].equals( args[ 1 ] ) ) { System.out.println( "Cannot copy to self" ); return; } else fileOut = new PrintWriter( new BufferedWriter( new FileWriter( args[ 1 ] ) ) ); fileIn = new BufferedReader( new FileReader( args[ 0 ] ) ); String oneLine; int lineNum = 0; while( ( oneLine = fileIn.readLine( ) ) != null ) { fileOut.print( ++lineNum + "\t"); fileOut.println( oneLine ); } } catch( IOException e ) { e.printStackTrace( ); } finally { try { if( fileIn != null ) fileIn.close( ); } catch( IOException e ) { e.printStackTrace( ); } try { if( fileOut != null ) ((Writer)fileOut).close( ); } catch( IOException e ) { e.printStackTrace( ); } } } }