Get file in the resources folder in Java

2019-04-07 11:08发布

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

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?

6条回答
beautiful°
2楼-- · 2019-04-07 11:31

You need to give the path of your res folder.

MyClass.class.getResource("/res/path/to/the/file/myFile.xsd").getPath();
查看更多
叛逆
3楼-- · 2019-04-07 11:31

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):

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;
    }
}
查看更多
Root(大扎)
4楼-- · 2019-04-07 11:37

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

/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.

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.

查看更多
不美不萌又怎样
5楼-- · 2019-04-07 11:40

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();
查看更多
手持菜刀,她持情操
6楼-- · 2019-04-07 11:44

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.

However if you do not want to use resources, you can use a zip file system. However Files.copy would suffice to copy the file outside the jar. Modifying the file inside the 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")).

查看更多
Juvenile、少年°
7楼-- · 2019-04-07 11:56

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

查看更多
登录 后发表回答