简体   繁体   中英

How to load resource file in Java?

I have the following source structure:

src
    resources
        config.properties
        data.txt

I copy these files into my jar, without flattening. So the jar contains resources/config.properties and resources/data.txt

The config.properties works fine while running locally (Eclipse: Run as | Run Configurations) and executing the jar.

private static final String CONFIGURATION_FILE_PATH = "resources/config.properties";
resourceInputStream = classLoader.getResourceAsStream(CONFIGURATION_FILE_PATH);
configurationProperties.load(resourceInputStream);

The data.txt file works locally (Eclipse: Run as | Run Configurations) but is not found when executing jar. I do need the File object created, as I then pass it to a third party library.

private static final String DATA_FILE_PATH = "resources/data.txt";
URL resourceUrl = classLoader.getResource(DATA_FILE_PATH);
File file = resourceUrl == null ? null : new File(resourceUrl.getPath());

when executing the jar, file is null.

Is it an execution issue?

I'm calling the jar from Jenkins jar /build/myapp.jar . Should I be setting class path for this execution? I mean the -cp switch..?

Open to other load options

As mentioned above, the config.properties loads fine. I don't need my data.txt to load with getResource . I'm open to other methods. As long as I can get a File from it.

For Java resources, you have to start the resource name with a slash to make it absolute or relative to the top of your Jar hierarchy.

Resource names that do not start with a slash are relative to the current location (package name/directory) of the class that loads them.

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