14

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?

3 Answers 3

10

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).

1
  • Been searching for this for 1 week, everywhere they said use Main.class.getProtectionDomain().getCodeSource(), which DOES NOT WORK!!! at least not on Mac from inside the Contents of an .app file... But this finally solved my problem... Thank you a lot... Commented Jul 21, 2012 at 7:32
6

#2 is the "user.dir" system property. #3 is the "user.home" property.

#4 is a bit of a kludge no matter how you approach it. Here's an alternate technique that works if you have a class loaded from a JAR not on the system classpath.

CodeSource src = MyClass.class.getProtectionDomain().getCodeSource();
if (src != null) {
  URL url = new URL(src.getLocation(), "MyApp.properties");
  ...
} 
else {
  /* Fail... */
}
1
  • 1
    @erickson it works! but if I have MyApp.properties inside a jar and in the external directory(not inside any package). Then how to read it?
    – Achyut
    Commented Oct 1, 2013 at 16:23
6

For the current working directory:

new File(".");

For a file named MyApp.properties in the current directory:

new File(new File("."), "MyApp.properties");
1
  • 3
    That works, but even shorter is to pass empty string (new File(""))
    – StaxMan
    Commented Apr 22, 2009 at 3:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.