// FileprintCountingCharacters.java Copyright (c) 2006 Kari Laitinen // http://www.naturalprogramming.com // 2006-02-16 File created. // 2006-02-16 Last modification. // A solution to Exercise 14-1. import java.io.* ; import java.util.* ; class FileprintCountingCharacters { public static void main( String[] not_in_use ) { Scanner keyboard = new Scanner( System.in ) ; System.out.print( "\n This program prints the contents of a text" + "\n file to the screen. Give a file name: " ) ; String file_name_from_user = keyboard.nextLine() ; try { BufferedReader file_to_print = new BufferedReader( new FileReader( file_name_from_user ) ) ; int character_counter = 0 ; int line_counter = 0 ; boolean end_of_file_encountered = false ; while ( end_of_file_encountered == false ) { String text_line_from_file = file_to_print.readLine() ; if ( text_line_from_file == null ) { end_of_file_encountered = true ; } else { System.out.print( text_line_from_file + "\n" ) ; line_counter ++ ; // The line termination characters are not counted // because they are not present in text_line_from_file character_counter = character_counter + text_line_from_file.length() ; } } file_to_print.close() ; System.out.print( "\n " + line_counter + " lines printed." ) ; System.out.print( "\n " + character_counter + " characters were printed.\n" ) ; } catch ( FileNotFoundException caught_file_not_found_exception ) { System.out.print( "\n \"" + file_name_from_user + "\" not found.\n" ) ; } catch ( IOException caught_io_exception ) { System.out.print( "\n\n File reading error. \n" ) ; } } }