有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java readLine()返回null

“行数=4”表示它正在读取文本文件的所有4行。 但是“Line read=null”。我不知道readLine()方法为什么不读取第一行

import java.io.*;
public class TestLineRead {

  public static void main (String[] args)
  {
      try
      {
          File tmpFileIn = new File("C:/Java/Employees.txt");
          BufferedReader br = new BufferedReader (new InputStreamReader(
                  new FileInputStream(tmpFileIn)));

          LineNumberReader lnr = new LineNumberReader(br);
          int numOfLines = 0;

          while (lnr.readLine() != null) {
              numOfLines++;
          }

          String str = null;
          System.out.println("Number of lines = " + numOfLines);
          str = br.readLine();
          System.out.println("Line read = " + str);

          br.close();
      }
      catch (IOException e) { System.out.println("error: " + e.getMessage()); }

  } // close main
} // close Class

共 (1) 个答案

  1. # 1 楼答案

    I don't know why the readLine() method is not reading the first line.

    是的,当你数线的时候

    这个

    while (lnr.readLine() != null) {
        numOfLines++;
    }
    

    消耗线路。当没有多余的行时,它返回null