简体   繁体   中英

Resource loading using ClassLoader

I have a resource file I need to load at runtime...it is in src/main/resources

I have successfully loaded the file to an inputStream using :

LoadSAC.class.getClassLoader().getResourceAsStream("someFile.txt");

LoadSAC is the class name ...

However, PMD complains about this suggests I use

Thread.currentThread().getContextClassLoader().getResource(...)

I have tried numerous combinations and can never get the file to be located... Any thoughts... I have trolled a number of searches with plenty of suggestions but none seem to work...

Any thoughts ?

If someFile.txt is in the same folder than LoadSAC.java , you can do:

InputStream is = LoadSAC.class.getResourceAsStream("someFile.txt");

If someFile.txt is in a subfolder subdir , you can do:

InputStream is = LoadSAC.class.getResourceAsStream("subdir/someFile.txt");

If your method in LoadSAC.java is non-static, you can replace LoadSAC.class.getResourceAsStream... by getClass().getResourceAsStream...

Be careful when compiling with ant or maven , by default, only .java file are copied as .class files in the build directory.

You have to write some rules to include someFile.txt in the final jar .

In your resource directory, you can add a little helper class like this:

import java.io.InputStream;
import java.net.URL;

import javax.activation.DataSource;
import javax.activation.URLDataSource;

public abstract class ResourceHelper {

    public static URL getURL(String name) {
        return ResourceHelper.class.getResource(name);
    }

    public static InputStream getInputStream(String name) {
        return ResourceHelper.class.getResourceAsStream(name);
    }

    public static DataSource getDataSource(String name) {
        return new URLDataSource(getURL(name));
    }
}

In LoadSAC.java just call:

InputStream is = ResourceHelper.getInputStream("someFile.txt");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM