LineNumberReader setLineNumber不起作用

时间:2012-06-20 07:02:59

标签: java android

我使用LineNumberReader来读取文本文件,当调用setLineNumber和getLinenumber时它打印== 0但是当再次调用readLine时,我发生了怎样的事情我怎么能解决它 这是我的代码

    BufferedWriter writer = new BufferedWriter(new FileWriter("text.txt"));
    writer.write("This is a line1\n" +
            "This is a line2\n" +
            "This is a line3");
    writer.newLine();
    writer.close();
    File myFile = new File("text.txt");
    FileReader fileReader = new FileReader(myFile);
    LineNumberReader reader = new LineNumberReader(fileReader);

    // Read from the FileReader.
    String lineRead = "";
    while ((lineRead = reader.readLine()) != null) {
        System.out.println(lineRead);
    }

    // Determine the number of lines that were read.
    System.out.println("Total lines read: " +
            reader.getLineNumber());

    // Reset the number of lines read.
    reader.setLineNumber(0);
    System.out.println("Total lines read after reset: " +
            reader.getLineNumber());

    String lineRead2 = "";
    while ((lineRead2 = reader.readLine()) != null) {
        System.out.println(lineRead2);
    }
    System.out.println("End");
    // Close the LineNumberReader and FileReader.
    fileReader.close();
    reader.close();

感谢

1 个答案:

答案 0 :(得分:1)

您只是设置LineNumberReader的行号计数器,而不是基础流中的位置。请参阅Java's LineNumberReader class的文档。

您已经处理了流,因此对readLine()的后续调用将返回null。

如果您想重新播放该流,则必须致电fileReader.reset()reader.reset(),这将导致LineNumberReader为您的{{1}调用重置}}