在Java中,可以使用多种方法来读取文件的内容。以下是其中两种常用的方法:

  1. 使用BufferedReader类:这是一种逐行读取文件内容的方法。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {

    public static void main(String[] args) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader("文件路径"));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 使用Scanner类:这是一种逐词读取文件内容的方法。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile {

    public static void main(String[] args) {
        try {
            File file = new File("文件路径");
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

以上两种方法都需要提供文件的路径作为参数,并且需要使用try-catch语句来处理可能出现的文件读取异常

Java读取文件内容

原文地址: https://www.cveoy.top/t/topic/ijH7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录