Java 程序:逐行读取文件内容

要理解此示例,您应了解以下Java编程主题


示例 1:使用BufferedInputStream读取文件的Java程序

import java.io.BufferedInputStream;
import java.io.FileInputStream;

class Main {
  public static void main(String[] args) {
    try {

      // Creates a FileInputStream
      FileInputStream file = new FileInputStream("input.txt");

      // Creates a BufferedInputStream
      BufferedInputStream input = new BufferedInputStream(file);

      // Reads first byte from file
      int i = input .read();

      while (i != -1) {
        System.out.print((char) i);

        // Reads next byte from the file
        i = input.read();
      }
      input.close();
    }

    catch (Exception e) {
      e.getStackTrace();
    }
  }
}

输出

First Line
Second Line
Third Line
Fourth Line
Fifth Line

在上面的示例中,我们使用BufferedInputStream类从名为input.txt的文件中读取每一行。

注意:要运行此文件,您应该在当前工作目录中有一个名为input.txt的文件。


示例 2:使用BufferedReader读取文件的Java程序

import java.io.FileReader;
import java.io.BufferedReader;

class Main {
  public static void main(String[] args) {

    // Creates an array of character
    char[] array = new char[100];

    try {
      // Creates a FileReader
      FileReader file = new FileReader("input.txt");

      // Creates a BufferedReader
      BufferedReader input = new BufferedReader(file);

      // Reads characters
      input.read(array);
      System.out.println("Data in the file: ");
      System.out.println(array);

      // Closes the reader
      input.close();
    }

    catch(Exception e) {
      e.getStackTrace();
    }
  }
}

输出

Data in the file: 
First Line
Second Line
Third Line
Fourth Line
Fifth Line

在上面的示例中,我们使用了BufferedReader类来读取名为input.txt的文件。


示例 3:使用Scanner读取文件的Java程序

import java.io.File;
import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    try {
      // create a new file object
      File file = new File("input.txt");

      // create an object of Scanner
      // associated with the file
      Scanner sc = new Scanner(file);

      // read each line from file and print it
      System.out.println("Reading File Using Scanner:");
      while(sc.hasNextLine()) {
        System.out.println(sc.nextLine());
      }

      // close scanner
      sc.close();
    } catch (Exception e) {
      e.getStackTrace();
    }
  }
}

输出

Reading File Using Scanner:
First Line
Second Line
Third Line
Fourth Line
Fifth Line

在上面的示例中,我们创建了一个名为fileFile类对象。然后,我们创建了一个与file关联的Scanner对象。

在这里,我们使用了Scanner的方法

  • hasNextLine() - 如果文件中存在下一行,则返回true
  • nextLine() - 从文件中返回整行

要了解更多关于Scanner的信息,请访问Java Scanner

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战