加載一個文件有一個在我的戰爭JSON文件在以下位置無法在WEB-INF位置
WEB-INF/classes/META-INF/jsonFolder/file.json
我想使用的路徑和下面的方法來加載我的文件訪問文件。
public static File deserializeJSONFile() throws IOException {
File file = null;
OutputStream outStream = null;
String jsonPath = "jsonFolder/file.json";
try (InputStream inputStream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(jsonPath)) {
in = inputStream;
if (in != null) {
byte[] bufferArray = new byte[in.available()];
in.read(bufferArray);
file = new File("tempJsonFile.json");
outStream = new FileOutputStream(file);
outStream.write(bufferArray);
}
} finally {
if (outStream != null) {
outStream.close();
}
}
if (null == in) {
String errorMessage = "JSON file: " + jsonPath + " could not be loaded";
FileNotFoundException fileNotFoundException = new FileNotFoundException(errorMessage);
logger.error(errorMessage, fileNotFoundException);
throw fileNotFoundException;
}
return file ;
}
所有我的單元測試通過。在部署我的應用程序時,我發現該文件沒有找到jsonFolder/file.json的異常。當我將實際位置追蹤到它正在查找的位置時,它正在查看,
C:\Program Files\eclipse-mars\jsonFolder\file.json
這是不正確的。我嘗試了不同的類加載器方法,但它沒有幫助。一個規則是我不應該修改pom.xml來完成這項工作。我如何加載文件?
你能告訴我們正確的代碼嗎?此代碼不能編譯,因爲它缺少'「'S和';單曲 –
添加的代碼 – yellow
這仍然是無效的:'字符串jsonPath = jsonFolder/file.json' –