Search code examples
javabufferedreaderfilereader

Loop a search for a string using BufferedReaders?


I'm using two BufferedReaders, one to read a document, and another one to get the input of the String to search from user, heeding the advice here. Here's the code so far:

import java.io.*;
import java.util.*;

public class Ejercicio6 {

    public static void main(String[] args) {

        Character answer = 'S'; 
        boolean exit = false;
        String name;
        String line;
        Scanner sc = new Scanner (System.in);
        boolean found = false;

        File file = new File ("/test/Ejercicio6/nombres.txt");

        try {

            do{

                exit = false;
                FileInputStream fis = new FileInputStream(file);
                BufferedReader readFile = new BufferedReader(new FileReader(file));
                BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("Search a name, I'll tell you if it's found:");
                name = userInput.readLine();
                while ((line = readFile.readLine()) != null && found == false){
                    if(line.equals(name)) {
                        found = true;
                    }else
                        found = false;
                }

                if (found == true)
                    System.out.println("I have found the name " +name+ " in the file " +file.getName());
                if (found == false)
                        System.out.println("Can't find the name");
                fis.getChannel().position(0);
                fileRead = new BufferedReader(new InputStreamReader(fis));

                System.out.println("Do you want to try again? (Y/N)");
                answer = sc.nextLine().toUpperCase().charAt(0);
                if (answer =='S'){

                    exit = false;
                }else

                    exit = true;
                fileRead.close();
            }while (exit == false);

//      }catch (FileNotFoundException e) {
//          e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();

        }

    }

}

There are 3 names on the document, but I always get the "name found" print, regardless of the input matching or not. I'm trying to figure out how does the getChannel() and the buffer clearing, as told here, but I'm having lots of trouble. What I'm missing?


Solution

  • You need to unset your flag found to false again after you're printing for matched or unmatched name. Just add

    found = false;

    before

    fis.getChannel().position(0);