Search the input file line by line for a given string. The output must contain the line number, followed by the contents of the line that contains the search argument. For instance given the following the search string: Java, the program would search the file line by line generating a result such as the following:

50: on the island of Java

95: The people of JAVA loves jaVa.

Use recursion to search the file.

Respuesta :

Answer:

    public void search(String key) throws FileNotFoundException, IOException

    {

         try (BufferedReader br = new BufferedReader(new FileReader(infile)))

         {

              Recursion recursionObject=new Recursion();

              int total_lines=1;

              StringTokenizer st ;

              String line;

              System.out.println("\n-----------------\n");

              while ((line = br.readLine()) != null)

              {

                   st=new StringTokenizer(line);

                   if(recursionObject.search(st, key))

                   {                  

                        System.out.println(total_lines+" : "+line);

                   }              

                   total_lines++;        

              }

         }

    }

Explanation:

  • Create a function named search that takes key as a parameter.
  • Read the file using the BufferedReader object inside the try block in case any exception occur.
  • Initialize the necessary variables and run a while loop until the line variable is not equal to null.
  • Check if the desired word is found and the display the results.
  • Lastly increment the total_lines counter.