Java, FileReader() 好像只读取文本文档的第一行?

Java, FileReader() only seems to be reading the first line of text document?

我还在学习中,所以如果我有误解请指正,但 FileReader 对象 return 不应该是文本文件的全部内容吗?

我这里有一段代码,我很简单地尝试获取一个简短的 .txt 文件的内容,并使用 system.out.println()

打印它
public class Main {

  public static void main(String[] args) throws FileNotFoundException, IOException {

    File testDoc = new File("C:\Users\Te\Documents\TestDocument.txt");
    BufferedReader reader = new BufferedReader(new FileReader(testDoc));
    Scanner in = new Scanner(new FileReader(testDoc));


    try {
      System.out.println(reader.readLine());
    } finally {
      reader.close();
    }
  }
}

.txt 文件仅包含 3 行,格式如下:

some text here, more text and stuff
new estonian lessons
word = new word

但是程序只打印文件中的第一行。

some text here, more text and stuff

这是什么原因造成的,我该如何纠正?

我已经尝试阅读文档,并通过 Whosebug 进行搜索,但我一直无法找到解决此问题的方法。

方法readLine()只是returns一行。所以你必须遍历所有行:

while(reader.hasNextLine()){
    String currentLine = reader.readLine();
}

BufferedReader's (look here) readLine()从文件中读取一行,所以需要写一个循环如下图:

String line = "";
 while((line =reader.readLine()) != null) {
        System.out.println(line);
 }

此外,您的代码中不需要 Scanner 对象(如果您使用 BufferedReader),因此它会简单如下所示:

        File testDoc = new File("C:\Users\Te\Documents\TestDocument.txt");
        BufferedReader reader = new BufferedReader(new FileReader(testDoc));
        try {
             String line = "";
             while((line =reader.readLine()) != null) {
                 System.out.println(line);
             }
        } finally {
          reader.close();
        }

两种方法。见下文。

 File testDoc = new File("C:\Users\Te\Documents\TestDocument.txt");
    BufferedReader reader = new BufferedReader(new FileReader(testDoc));
    Scanner in = new Scanner(new FileReader(testDoc));
    try {

      //Using Scanner Object
      while(in.hasNextLine()){
          System.out.println(in.nextLine());
      }

    //Using BufferReader Object
      String line=reader.readLine();
      while(line!=null){
          System.out.println(line);
          line=reader.readLine();
      }

    } finally {
      reader.close();
    }

您可以使用实际实例化但未用于将其与 FileReader 实例链接的 Scanner。
它可以允许具有 [=12] 的灵活 api =] class 有 hasNextLine()nextLine() 方法。

Scanner in = new Scanner(new FileReader(testDoc));


public static void main(String[] args) throws FileNotFoundException, IOException {

    File testDoc = new File("C:\TestDocument.txt");
    Scanner in = new Scanner(new FileReader(testDoc));

    try {
        while (in.hasNextLine()) {
            String currentLine = in.nextLine();
            System.out.println(currentLine);
        }
    } finally {
        in.close();
    }
}