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();
}
}
添加回答
舉報