简体   繁体   中英

ClassLoader.getResourceAsStream can't find resource in JAR file

I have a Java project in Eclipse with several classes with main methods, and a resource folder with properties. The resource folder, which contains 'config/config.properties', is in the Build Path (right-click the resource folder in Project Explorer in Eclipse->Build Path->Add to Build Path). I can run the classes with main methods fine from Eclipse and the resources are properly loaded. I am generating a runnable JAR file from one of the classes with a main method (right-click on the Java class file in Package Explorer->Export->Java/Runnable JAR file). When I execute the JAR file ('java -jar myApp.jar') ClassLoader.getResourceAsStream("config/config.properties") returns null. I have tried prepending several numbers of '../' to the properties file path but (1) this does not work and (2) it breaks execution for running in Eclipse. The application takes no parameters on the command line. Any ideas what the problem is?

Do you have a META-INF/MANIFEST.MF file in your jar?

Add the following line to the file:

Class-Path: .

Don't forget an empty line after that. I had a similar problem a couple of years ago.

More info on the manifest.mf file

Try exporting the jar using the Jar Export Wizard. You can open it by right clicking -> "Export" -> "Jar file" (as opposed to "Runnable JAR file").

This will allow you to individually select each file you want to include.

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