1

I'm not sure if I'm confused from my c++ background but...

I'm writing(learning) a Java application that will load in a text file with configuration date. Kindof like an INI file.

The actual reading & processing of the file I think I can handle. It's the file location that is stumping me.

I want to have this extra text file stored in the same directory as the jar application file. However, I won't know for sure where this application file is on the client computer - as in what directory. And, as I need the full path to ensure loading of the file, I need a way to programatically find the path to the jar file at run-time.

Looking around I thought I found something, but in testing it was giving me the location to the class file that was calling it:

String applicationDir = getClass().getProtectionDomain().getCodeSource().getLocation().getPath(); 

if (applicationDir.endsWith(".exe"))
{
    applicationDir = new File(applicationDir).getParent();
}
else
{
    // Add the path to the class files  
    applicationDir += getClass().getName().replace('.', '/');

    // Step one level up as we are only interested in the 
    // directory containing the class files
    applicationDir = new File(applicationDir).getParent();
} 

So, what else can I do to find the actual path to the jar file? (And not the current working directory either, as that can change, so System.getProperty("user.dir") doesn't work for me either)

Dave
  • 1,696
  • 4
  • 23
  • 47
  • Maybe [this previous answer](http://stackoverflow.com/questions/778187/getting-directory-path-to-class-file-containing-main/778246#778246) will help. – LoSciamano Jun 07 '11 at 09:31

1 Answers1

1

You can put your ini (in java we use resource bundles - .properties - actually) in classpath and load it via ClassLoader.

edit: If you decide to use resource bundles, you can skip using classloader directly, see this

user124
  • 1,632
  • 1
  • 11
  • 11
  • Yes, I was aware of properties files (although haven't used them yet). However, as I'm doing this as kind of a learning exercise of working with external files, I still need to work out the path to the jar. – Dave Jun 07 '11 at 10:34