Skip to content
Advertisement

how to properly check if a string is in txt file

I’m writing a program that manages a library. This part of the program is where you borrow a book, but only if it’s in the library, so I check if the book is in the library but it always comes back negative even if the string is in the library txt file.

FileReader fileInvc = new FileReader("library.txt");
        BufferedReader readervc = new BufferedReader(fileInvc);
        String linevc;
        String readvc=readervc.readLine();
        if((linevc = readvc) != null) {
            if((linevc.contains(book))) {
                // what happens after weve found out that the book is the library txt file
            }else{
                System.out.println("libray does not contain this book");
            }
        }else{
            System.out.println("error retry");
        }

What should I do?

Advertisement

Answer

You are just checking the first line. If you want to check if the book exists anywhere in the file, you need to continue reading it until you find the book or until you reach the end of the file:

private static boolean isInFile(String book) {
    try (FileReader fileInvc = new FileReader("library.txt");
         BufferedReader readervc = new BufferedReader(fileInvc)) {
         String readvc = readervc.readLine();
         while (readvc != null) {
             if (readvc.contains(book)) {
                 return true;
             }
             readvc = readervc.readLine();
         }
         return false; 
    }
}

Note that using Files.lines could easier than using a reader:

private static boolean isInFile(String book) {
    return Files.lines(Paths.get("library.txt")).anyMatch(l -> l.contains(book));
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement