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
147 views
in Technique[技术] by (71.8m points)

java - Accessing properties files outside the .jar?

I have a .jar file I'm putting together. I want to create a really really simple .properties file with configurable things like the user's name & other stuff, so that they can hand-edit rather than my having to include a GUI editor.

What I'd like to do is to be able to search, in this order:

  1. a specified properties file (args[0])
  2. MyApp.properties in the current directory (the directory from which Java was called)
  3. MyApp.properties in the user's directory (the user.home system property?)
  4. MyApp.properties in the directory where the application .jar is stored

I know how to access #1 and #3 (I think), but how can I determine at runtime #2 and #4?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

For 4, you could try this. Get the classpath:

String classpath = System.getProperty("java.class.path");

Then search it for the name of your application jar:

int jarPos = classpath.indexOf("application.jar");

Parse out the path leading up to it:

int jarPathPos = classpath.lastIndexOf(File.pathSeparatorChar, jarPos) + 1;
String path = classpath.substring(jarPathPos, jarPos);

Then append MyApp.properties. Make sure to check for jarPos == -1, meaning the jar isn't found if the classpath (perhaps when running in your dev environment).


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

...