Get file in the resources folder in Java

23,303

Solution 1

You need to give the path of your res folder.

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

Solution 2

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();

Solution 3

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;
    }
}
Share:
23,303
Malintha
Author by

Malintha

I am a software engineer in WSO2 Inc.

Updated on January 11, 2020

Comments

  • Malintha
    Malintha over 4 years

    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?