简体   繁体   中英

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 "***".

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM