簡體   English   中英

Jar 沒有加載資源文件

[英]Jar is not loading resources file

我有一個項目,其中有一個文件夾“src/main/resources”,其中有休眠配置文件,我使用這行代碼加載它

HibernateUtil.class.getResource("/hibernate.cgf.xml").getPath()

從 IDE 內部它運行良好,但是當我創建 jar 時它不會歸檔文件。

我怎樣才能在jar文件中正確加載它?

謝謝

你能試試這個:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("fileName").getFile());

在不知道您如何准確使用通過以下方式提取的路徑的情況下,我不能說這是問題所在:

HibernateUtil.class.getResource("/hibernate.cgf.xml").getPath()

但我可以告訴你:

從 IDE 運行,上面的代碼行將返回:

/path/to/project/src/main/resources/hibernate.cgf.xml

這是一個有效的文件系統路徑。 例如,您可以使用此路徑創建File類的實例,然后使用該實例讀取文件內容。

但是,從 jar 文件內部運行的同一行代碼將返回:

file:/path/to/jar/jar_name.jar!/hibernate.cgf.xml

這不是有效的文件系統路徑。 如果您使用此路徑創建File類的實例,然后嘗試讀取文件的內容,您將得到一個異常: java.io.FileNotFoundExeption

要從 jar 中讀取文件的內容,您應該使用方法Class.getResourceAsStream(String) ,它將返回類sun.net.www.protocol.jar.JarURLConnection.JarURLInputStream的實例(或非 Oracle 中的等價物或非 OpenJDK Java)。 然后,您可以使用此對象來讀取文件的內容。 例如:

InputStream inputStream = HibernateUtil.class.getResourceAsStream("/hibernate.cgf.xml");
Scanner scanner = new Scanner(inputStream).useDelimiter("\\A");
String fileContents = scanner.hasNext() ? sscanner.next() : "";

最有可能的是,您創建的 jar 中不存在該文件。 您的問題中的信息太少,但我會嘗試猜測:

您的 hibernate.cgf.xml 與 Java 源文件位於同一目錄中,並且您正在使用期望資源存儲在單獨目錄中的構建工具(無論是 IDE、maven、gradle 還是 ant 腳本)。

很容易檢查:嘗試解壓縮您的 jar 並查看文件是否存在(使用任何工具,您可以將擴展名從 .jar 更改為 .zip)。 我想你會看到文件不存在。

然后回到一個問題:“如何使用 XXX 將我的非 Java 資源打包到 jar 中”,其中 XXX 將是您用於構建 jar 的技術的名稱。

如果hibernate.cgf.xml與 HibernateUtil 類在同一個包中,則很可能不需要"/hibernate.cgf.xml"中的斜線。

您實際上也可以使用完整路徑通過類加載器訪問該文件。 但是,您永遠不會添加第一個斜線。

下面是一些代碼,演示了如何使用不同的方法訪問文件:

public static void main(String[] args) {
    // Accessing via class
    System.out.println(SimpleTests.class.getResource("hibernate.cgf.xml").getPath());
    // Accessing via classloader from the current thread
    String path = Thread.currentThread().getContextClassLoader()
            .getResource("simple/hibernate.cgf.xml").getPath();
    System.out.println(path);
    // Accessing via classloader used by the current class
    System.out.println(SimpleTests.class.getClassLoader().getResource("simple/hibernate.cgf.xml").getPath());
}

在上面的示例中,“simple”包應該替換為hibernate.cgf.xml所在的包。 但是你不應該在包聲明的開頭有斜線。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM