Search code examples
javaseleniumfor-loopforeachreadfile

Eclipse Java - For each line loop


I want to read a file, and I did it, but I want to read it line by line, beacuse after I read the file I need to do a "for each line loop". So far I did this:

File file = new File ("C:\\WebDrivers\\lex.txt");
Scanner scan = new Scanner(file);

while(scan.hasNextLine()) {
    String serv= scan.nextLine();
    System.out.println(serv);

    for(String sv : serv) {
        driver.findElement(By.className("inline-search")).sendKeys(sv);
    }
}

I get an error in the last "for loop", because I can only iterate over an array. How can I fix this?


Solution

  • Just write for (String sv : serv.split("\n")). That will split the string into an array of lines that you can iterate over.