开发者

Locating an external file in Java

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 te开发者_运维技巧xt 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)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜