简体   繁体   中英

How to read a line from text file, call function on that line and move to second line and so on?

Forgive me if the question is stupid, but I cannot move the reader to a second line. Calling function on every input line is important.

BufferedReader reader = null;
try {
    reader = new BufferedReader(new FileReader("input.txt"));
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
while ((reader.readLine()) != null) {

    ///////////

}

You just need to store the value returned by reader.readLine into an additional variable (just like I said in my comment). Modify your code to look like the following:

String line = null;
while ((line = reader.readLine()) != null) {
    //use "line" as per your needs
}

Try that:

BufferedReader reader = null;
try {
    String line;
    reader = new BufferedReader(new FileReader("input.txt"));
    while ((line = reader.readLine()) != null) {
        myFunc (line);
    }
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} finally {
    if (reader!=null)
        try {
            reader.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
}

You can also use a Scanner instead:

File file = new File ("input.txt");
Scanner scanner = null;
try {
    scanner = new Scanner(file);

    while (scanner.hasNextLine()) {
        myFunc (scanner.nextLine());
    }
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} finally {
    if (scanner!=null)
        scanner.close();
}

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