如何从文本文件中读取一行,在该行上调用函数并移动到第二行,依此类推?

时间:2014-03-07 22:58:40

标签: java sockets bufferedreader

如果问题很愚蠢,请原谅我,但我无法将读者移到第二行。在每个输入线上调用函数很重要。

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) {

    ///////////

}

2 个答案:

答案 0 :(得分:0)

您只需将reader.readLine返回的值存储到另一个变量中(就像我在评论中所说的那样)。将代码修改为如下所示:

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

答案 1 :(得分:0)

试试:

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

您也可以使用Scanner代替:

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