2 回答

TA贡献1872条经验 获得超4个赞
ClassLoader loader = myClass.class.getClassLoader();
URL url = loader.getResource(location);
上面的代码仅适用于类路径中存在的文件。因此,您可以将其更改为默认从 src/main/resources 目录读取,并通过将其更新为用户给出的绝对路径:
try {
return new File(location).listFiles();
} catch (NullPointerException e) {
throw new FileNotFoundException();
}

TA贡献1856条经验 获得超5个赞
这很简单:
ClassLoader cl = myClass.class.getClassLoader();
URL url = cl.getResource(location);
if (url == null) {
//the location does not exist in class path
return new File(location).listFiles();
} else {
return new File(url.getPath()).listFiles();
}
但我认为更好的方法是:
private File[] readFile(String userLocation) {
if(userLocation == null || userLocation.isEmpty()) {
// user do not specify the path
return new File(myClass.class.getResource("data").getPath()).listFiles();
} else {
return new File(userLocation).listFiles();
}
}
添加回答
举报