简体   繁体   中英

How to get filepath of the located file when ran from JAR in JAVA?

My project has the following structure:

src/test/resources/utility/configuration.xml

I am trying to get the file location in the system using ClassLoader

public File getFileFromResources(String fileName){

        ClassLoader classLoader = getClass().getClassLoader();

        URL resource = classLoader.getResource(fileName);
        if(resource == null){
            throw new IllegalArgumentException("file not found");
        }else{
            return new File(resource.getFile());
        }

Calling method:

File file = getFileFromResources("Utility/ConfigurationXML.xml");
strFilePath = file.getAbsolutePath();

which gives me the absolute path of the file, which is in the target folder.

The above code works fine in eclipse IDE, but when I created the project JAR, getFileFromResources() returns me

file:/C:/Users/UserName/Desktop/ExecutableJAR/TestJAR-tests.jar!/Utility/ConfigurationXML.xml

I am using Maven to build my project.

As your path indicates, the respurce is part of yout test resources. Test resources can't be accessed by production code (while test code can access production resources). If you need this particular resource in production, then you need to move it to your production resources folder hierarcy (that would usually be src/main/resources/utility/configuration.xml .

Test Resources (and classes) are not included in a JAR file because that's considered production code.

As @Nicktar stated that "Test resources can't be accessed by production code"

There's no standard for anything at the root level called resources.

src/main/resources is normally where you put non-Java artifacts that should be moved into the normal package hierarchy, like XML config files loaded as classpath resources.

I have get the same problem wene using netbeans (it does'n work from command line java -jar jarname.jar )
I end up puting my ressource file in a folder in the root of the project then after building the jar I move that folder to the same plase as the jar file.
and it work

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