You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中Files.readAllLines报错无提示,请求排查代码问题

问题分析与解决

你的代码核心问题是未处理Files.readAllLines()抛出的检查型异常:

  • Files.readAllLines()方法在文件不存在、无读取权限或发生IO错误时会抛出IOException,这是Java的检查型异常,要求必须显式处理——要么用try-catch捕获,要么在方法声明里用throws抛出。
  • 你的main方法既没声明抛出该异常,也没捕获处理,所以编译器会直接报错,只是你可能没留意到编译提示。

另外还有个冗余操作:你提前用new ArrayList<String>()初始化code完全没必要,因为Files.readAllLines()会直接返回一个List实例,之前的初始化对象会被直接覆盖,属于无效内存占用。


方案1:在main方法声明中抛出异常

这种方式适合简单测试场景,把异常交给JVM处理:

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.Scanner;
import java.util.List;
import java.io.IOException; // 必须导入IOException类

public class NDBall {
    public static Scanner scanner = new Scanner(System.in);

    public static void main(String args[]) throws IOException {
        String input = scanner.nextLine();
        Path path = Paths.get(input);
        List<String> code = Files.readAllLines(path);
        // 后续可添加对读取内容的处理逻辑
    }
}

方案2:用try-catch捕获并处理异常

这种方式更健壮,出错时能给出具体提示,方便排查问题:

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.Scanner;
import java.util.List;
import java.io.IOException;

public class NDBall {
    public static Scanner scanner = new Scanner(System.in);

    public static void main(String args[]) {
        String input = scanner.nextLine();
        Path path = Paths.get(input);
        List<String> code = null;
        
        try {
            code = Files.readAllLines(path);
            // 在这里处理读取到的代码内容
        } catch (IOException e) {
            // 打印错误信息,帮你定位问题(比如路径错误、无读取权限)
            System.err.println("文件读取失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

内容的提问来源于stack exchange,提问作者DKrazy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 03:24:27