2017-06-05 98 views
0

我嘗試從我的應用程序讀取資源文件,但它不起作用。Java獲取資源不起作用

代碼:

文件:/ C:/Users/username/Repo/run/Application.jar /test.xsd當我執行的jar文件

String filename = getClass().getClassLoader().getResource("test.xsd").getFile(); 
System.out.println(filename); 
File file = new File(filename); 
System.out.println(file.exists()); 

輸出

,當我從運行的IntelliJ應用程序,但不是當我執行的jar文件它的工作原理。如果我用7-zip打開我的jar文件,test.xsd位於根文件夾中。爲什麼執行jar文件時代碼不工作?

+0

嘗試移動「test.xsd」入類文件夾。如你所見,你調用getClassLoader()來搜索類路徑中的文件。 –

+0

你可以檢查jar的內容,你的文件是否打包到jar中 –

+0

IntelliJ可能已經添加了你的根文件夾作爲類路徑 –

回答

1

另外,File是指實際的OS文件系統文件;在操作系統的文件系統中,只有一個jar文件,該jar文件不是文件夾。您應該將URL的內容提取到臨時文件,或者使用字節在內存中或作爲流進行操作。

請注意,myURL.getFile()返回字符串表示形式,而不是實際的File。以類似的方式,這將工作:

File f = new URL("http://www.example.com/docs/resource1.html").getFile(); 
f.exists(); // always false - will not be found in the local filesystem 

一個很好的包裝可能是以下幾點:

public static File openResourceAsTempFile(ClassLoader loader, String resourceName) 
     throws IOException { 
    Path tmpPath = Files.createTempFile(null, null); 
    try (InputStream is = loader.getResourceAsStream(resourceName)) { 
     Files.copy(is, tmpPath, StandardCopyOption.REPLACE_EXISTING); 
     return tmpPath.toFile(); 
    } catch (Exception e) { 
     if (Files.exists(tmpPath)) Files.delete(tmpPath); 
     throw new IOException("Could not create temp file '" + tmpPath 
       + "' for resource '" + resourceName + "': " + e, e); 
    } 
} 
+0

URL url = getClass()。getClassLoader()。getResource(「/ test.xsd」);給url null。 – user1766169

+0

嗯,你是對的。在我上一個項目中是必要的,但我無法重現這種行爲。我編輯了該部分,並添加了示例代碼以將資源複製到臨時文件,以解決您的問題。請記住在完成後刪除臨時文件! – tucuxi