在Java中获取资源文件夹中的文件

7
我想在我的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仓库依赖中获得了文件路径,但是找不到该文件。我该怎么做?

6个回答

4
你需要提供你的res文件夹的路径。
MyClass.class.getResource("/res/path/to/the/file/myFile.xsd").getPath();

3

您的资源目录在类路径中吗?

您没有将资源目录包含在路径中:

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

1
从资源文件夹构建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;
    }
}

0

无法访问其他Maven模块的资源。因此,您需要在src/main/resourcessrc/test/resources文件夹中提供您的资源myFile.xsd。


0

虽然路径是正确的,但它不在文件系统中,而是在 jar 包内。这是因为 jar 包正在运行。永远不能保证资源是一个文件。

不过,如果你不想使用资源,可以使用 zip 文件系统。但是,Files.copy足以将文件复制到 jar 包外。在 jar 包内修改文件是个坏主意,最好将资源用作“模板”,在用户的主目录(子目录)中制作初始副本(System.getProperty("user.home"))。


0
在Maven项目中,假设我们有一个名为"config.cnf"的文件,它的位置如下。
/src
  /main
   /resources
      /conf
          config.cnf

在IDE(Eclipse)中,我使用ClassLoader.getResource(..)方法访问此文件,但如果我使用jar运行此应用程序,则始终会遇到“File not found”异常。最后,我编写了一种方法,通过查看应用程序工作的位置来访问该文件。
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中访问此文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接