我使用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();


谢谢

最佳答案

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

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

如果要重新读取流,则必须调用fileReader.reset()reader.reset(),这将导致LineNumberReader调用FileReader的重置。

10-08 07:39