Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

java - Load resource from anywhere in classpath

I have a simple java application that loads a properties file from the current package.

this.getClass().getResourceAsStream("props.properties");

This works fine when the property file I want is in the current package. However, I want to package this application as a JAR and define and override with a new properties file where I use it. Is there a way to load the first resource named "props.properties" that is on the classpath?

I want it to be as easy to override the properties file via command line:

java.exe -classpath props.properties;myJar.jar com.test.MyApp

I don't want to have to unpack the JAR and modify the properties file to change something. I feel like I'm missing something obvious...

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The javadoc for Class.getResourceAsStream() documents the lookup logic:

If the name begins with a '/' ('u002f'), then the absolute name of the resource is the portion of the name following the '/'.

Otherwise, the absolute name is of the following form:
modified_package_name/name

Where the modified_package_name is the package name of this object with '/' substituted for '.' ('u002e').

So in other words, the resource name passed to the method should look like /com/package/p2/props.properties if the props.properties is stored in the com.package.p2 package instead of the current class's.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...