传入仓库根路径读取JSON文件时抛出IllegalArgumentException异常
问题分析与解决方案
异常核心原因排查
你遇到的IllegalArgumentException,在File.listFiles()调用场景下,大概率是以下两个问题导致:
- 路径拼写错误:你传入的仓库根路径写的是
my-app-1/src/main/resouces/my_directory,其中resouces少了一个字母r,正确拼写应为resources,这是最可能触发异常的点。 - 相对路径基准不匹配:运行程序时的当前工作目录如果已经是
my-app-1内部,再传入my-app-1/...会形成不存在的嵌套路径,导致目录无法识别。
具体修复步骤
- 修正路径拼写:把路径中的
resouces改为resources,这是首要解决的问题。 - 增加目录合法性校验:在调用
listFiles()前先判断目录是否存在且合法,避免无意义的异常抛出:private List<File> getFiles(String directoryPath) { File directory = new File(directoryPath); // 新增目录有效性检查 if (!directory.exists() || !directory.isDirectory()) { System.err.println("无效目录: " + directoryPath); return Collections.emptyList(); } File[] files = directory.listFiles((dir, name) -> name.endsWith(".json")); return files != null ? Arrays.asList(files) : Collections.emptyList(); } - 确认当前工作目录:通过
System.getProperty("user.dir")打印程序运行时的当前工作目录,确保传入的路径与当前目录匹配:- 如果当前目录是仓库根目录(包含
my-app-1的文件夹),则传入my-app-1/src/main/resources/my_directory是正确的; - 如果当前目录已经是
my-app-1内部,直接传入src/main/resources/my_directory即可。
- 如果当前目录是仓库根目录(包含
优化建议:使用Java NIO替代传统File类
Java NIO的Path和FilesAPI更健壮,错误反馈更清晰,推荐替换为以下实现:
import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; private List<File> getFiles(String directoryPath) { Path dirPath = Paths.get(directoryPath); if (!Files.exists(dirPath) || !Files.isDirectory(dirPath)) { return Collections.emptyList(); } try { return Files.list(dirPath) .filter(path -> path.getFileName().toString().endsWith(".json")) .map(Path::toFile) .collect(Collectors.toList()); } catch (IOException e) { e.printStackTrace(); return Collections.emptyList(); } }
内容的提问来源于stack exchange,提问作者webdudewithnoname
相关产品推荐
相关产品推荐

