Search code examples
javajava.util.scanner

How do I read multiple lines and end before a certain string using Scanner in Java?


I'm trying to read multiple lines from a text file before reaching a certain string, "***", which I would then like to print out. How do I do this? Code:

public void loadRandomClass(String filename) {
    try {
        Scanner scan = new Scanner(new File(filename));
        while((scan.hasNextLine()) && !(scan.nextLine().equals("***"))) {
        
        }
        scan.close();

    } catch (FileNotFoundException e) {
        System.out.println("Something went wrong");
        e.printStackTrace();
    }
    
}

I have tried some stuff, but it keeps skipping every 2nd line, starting from the 1st and it doesn't stop before "***".


Solution

  • The problem is that scan.nextLine() reads the line and deletes it from the buffer i suppose. Try this:

    
    while(scan.hasNextLine()) {
       String next = scan.nextLine();
       if(next.contains("***") break;
       System.out.println(next);
    }