Java教程

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

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

在这个例子中,我们将学习使用 Java 中的各种类来读取文件的内容。
要理解此示例,您应该了解以下Java 编程主题:
Java 文件类 Java BufferedInputStream 类 Java FileReader 类

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

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: Java 程序使用 BufferedReader 读取文件

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 Class来读取名为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 对象。
这里,我们使用了扫描仪方法
hasNextLine()-如果文件中有下一行,则返回 true nextLine()-从文件中返回整行
要了解有关扫描仪的更多信息,请访问 Java 扫描仪。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4