2017-09-15 21 views
0

加載一個文件有一個在我的戰爭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來完成這項工作。我如何加載文件?

+0

你能告訴我們正確的代碼嗎?此代碼不能編譯,因爲它缺少'「'S和';單曲 –

+0

添加的代碼 – yellow

+0

這仍然是無效的:'字符串jsonPath = jsonFolder/file.json' –

回答

0

有一個在我的戰爭JSON文件在以下位置

WEB-INF-γ>類 - > META-INF-γ> jsonFolder-> file.json

所以它的名字作爲資源是META-INF/jsonFolder/file.json。不是你的代碼中有什麼。

+0

正如我所說的,它在我的單元測試中可以正常工作,因爲它可以在我的目標文件夾中找到,當我打包到war中並將它部署到tomcat時,那就是當我看到這個錯誤時 – yellow

+0

java.io.FileNotFoundException :JSON文件:jsonFolder/file.json不能在.... NegotiationUtil.deserializeJsonFile(NegotiationUtil.java:71)在....這裏的ResourceManager加載 \t \t (ResourceManager.java:128) 。 deserializeJsonFile()我這是上面在try塊中顯示的實現。 – yellow

+1

所以你自己拋出這個異常?在代碼中看不到。當您不提供所有相關信息時很難提供幫助。 – EJP