// Search.java (c) 2005 Kari Laitinen // http://www.naturalprogramming.com // 2004-10-08 File created. // 2005-11-19 Last modification. // The best way to execute this program is to run it in a // command prompt window where command line parameters can // be given. It may be difficult, and even impossible, to // supply the command line parameters if this program is // executed with a modern development tool such as JCreator // or Eclipse. // This program will, though, ask for data from the user // if no command line parameters are given. import java.io.* ; import java.util.* ; class Search { static void search_string_in_file( String file_name_from_caller, String string_to_be_searched ) { try { BufferedReader file_to_read = new BufferedReader( new FileReader( file_name_from_caller ) ) ; System.out.print( "\n Searching ... \"" + string_to_be_searched + "\"\n" ) ; int line_counter = 0 ; boolean end_of_file_encountered = false ; while ( end_of_file_encountered == false ) { String text_line_from_file = file_to_read.readLine() ; if ( text_line_from_file == null ) { end_of_file_encountered = true ; } else { line_counter ++ ; if ( text_line_from_file.contains( string_to_be_searched ) ) { System.out.print( "\n String \"" + string_to_be_searched + "\" was found on line " + line_counter ) ; } } } file_to_read.close() ; } catch ( FileNotFoundException caught_file_not_found_exception ) { System.out.print( "\n Cannot open \"" + file_name_from_caller + "\""); } catch ( IOException caught_io_exception ) { System.out.print( "\n\n File processing error. \n" ) ; } } public static void main( String[] command_line_parameters ) { Scanner keyboard = new Scanner( System.in ) ; if ( command_line_parameters.length == 2 ) { search_string_in_file ( command_line_parameters[ 0 ], command_line_parameters[ 1 ] ) ; } else { System.out.print( "\n This program can search a string in a " + "\n text file. Give first the file name : " ) ; String file_name_given_by_user = keyboard.nextLine() ; System.out.print( "\n Type in the string to be searched: " ) ; String string_to_be_searched = keyboard.nextLine() ; search_string_in_file( file_name_given_by_user, string_to_be_searched ) ; } } }