Java读取文件可以使用Java的标准库中的File类和Scanner类。

  1. 使用File类读取文件
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("file.txt");
            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("文件不存在!");
        }
    }
}
  1. 使用Scanner类读取文件
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile {
    public static void main(String[] args) {
        try {
            Scanner scanner = new Scanner(new File("file.txt"));
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                System.out.println(line);
            }
            scanner.close();
        } catch (FileNotFoundException e) {
            System.out.println("文件不存在!");
        }
    }
}

以上两种方法都可以读取文件的内容并输出到控制台。需要注意的是,需要处理文件不存在的异常

java读取文件

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

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