簡體   English   中英

在Java中的resources文件夾中獲取文件

[英]Get file in the resources folder in Java

我想在我的Java項目的資源文件夾中讀取該文件。 我使用了以下代碼

MyClass.class.getResource("/myFile.xsd").getPath();

我想檢查文件的路徑。 但它給出了以下路徑

file:/home/malintha/.m2/repository/org/wso2/carbon/automation/org.wso2.carbon.automation.engine/4.2.0-SNAPSHOT/org.wso2.carbon.automation.engine-4.2.0-SNAPSHOT.jar!/myFile.xsd

我在maven存儲庫依賴項中獲取文件路徑,但它沒有獲取文件。 我怎樣才能做到這一點?

您需要提供res文件夾的路徑。

MyClass.class.getResource("/res/path/to/the/file/myFile.xsd").getPath();

您的資源目錄是否在類路徑中?

您沒有在路徑中包含資源目錄:

MyClass.class.getResource("/${YOUR_RES_DIR_HERE}/myFile.xsd").getPath();

從資源文件夾構造File實例的一種可靠方法是將資源作為流復制到臨時文件中(臨時文件將在JVM退出時刪除):

public static File getResourceAsFile(String resourcePath) {
    try {
        InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
        if (in == null) {
            return null;
        }

        File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
        tempFile.deleteOnExit();

        try (FileOutputStream out = new FileOutputStream(tempFile)) {
            //copy stream
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
        return tempFile;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

無法訪問其他maven模塊的資源。 因此,您需要在src/main/resourcessrc/test/resources文件夾中提供資源myFile.xsd。

路徑是正確的,雖然不在文件系統上,但在jar內。 也就是說,因為罐子正在運行。 資源永遠不會保證是文件。

但是,如果您不想使用資源,則可以使用zip文件系統 但是Files.copy就足以將文件復制到jar外部了。 修改里面的jar文件是一個壞主意。 最好使用資源作為“模板”在用戶的主(子)目錄( System.getProperty("user.home") )中創建初始副本。

在maven項目中,假設我們有一個名為“ config.cnf ”的文件,它的位置在下面。

/src
  /main
   /resources
      /conf
          config.cnf

在IDE(Eclipse)中,我使用ClassLoader.getResource(..)方法訪問此文件,但如果我使用jar運行此應用程序,我總是跨“未找到文件”異常。 最后,我寫了一個方法,通過查看應用程序的工作方式來訪問該文件。

public static File getResourceFile(String relativePath)
{
    File file = null;
    URL location = <Class>.class.getProtectionDomain().getCodeSource().getLocation();
    String codeLoaction = location.toString();
    try{
        if (codeLocation.endsWith(".jar"){
            //Call from jar
            Path path = Paths.get(location.toURI()).resolve("../classes/" + relativePath).normalize();
            file = path.toFile();
        }else{
            //Call from IDE
            file = new File(<Class>.class.getClassLoader().getResource(relativePath).getPath());
        }
    }catch(URISyntaxException ex){
        ex.printStackTrace();
    }
    return file;
}  

如果通過發送“ conf / config.conf ”參數調用此方法,則可以從jar和IDE訪問此文件。

暫無
暫無

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

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