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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19115837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 14:15:26  来源:igfitidea点击:

Get file in the resources folder in Java

javamavenresourcesclasspath

提问by Malintha

I want to read the file in my resource folder in my Java project. I used the following code for that

我想读取 Java 项目中资源文件夹中的文件。我为此使用了以下代码

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

And I wanted to check the path of the file. But it gives the following path

我想检查文件的路径。但它给出了以下路径

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

I get the file path in the maven repository dependency and it is not getting the file. How can I do this?

我在 maven 存储库依赖项中获取了文件路径,但它没有获取该文件。我怎样才能做到这一点?

回答by SudoRahul

You need to give the path of your resfolder.

您需要提供res文件夹的路径。

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

回答by Matt

Is your resource directory in the classpath?

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

You are not including resource directory in your path:

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

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

回答by Sebastian

It is not possible to access resources of other maven modules. So you need to provide your resource myFile.xsd in your src/main/resourcesor src/test/resourcesfolder.

无法访问其他 maven 模块的资源。所以你需要在你的src/main/resourcessrc/test/resources文件夹中提供你的资源 myFile.xsd 。

回答by Joop Eggen

The path is correct, though not on the file system, but inside the jar. That is, because the jar was running. A resource never is guaranteed to be a File.

路径是正确的,虽然不在文件系统上,但在 jar 内。也就是说,因为 jar 正在运行。资源永远不能保证是文件。

However if you do not want to use resources, you can use a zip file system. However Files.copywould suffice to copy the file outside the jar. Modifying the file insidethe jar is a bad idea. Better use the resource as "template" to make an initial copy in the user's home (sub-)directory (System.getProperty("user.home")).

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

回答by Lukas Masuch

A reliable way to construct a File instance from the resource folder is it to copy the resource as a stream into a temporary File (temp file will be deleted when the JVM exits):

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

回答by gbii

In maven project, lets assume that, we have the file whose name is "config.cnf" and it's location is below.

在 maven 项目中,让我们假设,我们有一个名为“ config.cnf”的文件,它的位置在下面。

/src
  /main
   /resources
      /conf
          config.cnf

In IDE (Eclipse), I access this file by using ClassLoader.getResource(..) method, but if I ran this application by using jar, I always across "File not found" exception. Finally, I wrote a method which accessing the file by looking at where app works.

在 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;
}  

If you call this method by sending "conf/config.conf" param, you access this file from both jar and IDE.

如果您通过发送“ conf/config.conf”参数调用此方法,则您可以从 jar 和 IDE 访问此文件。