5

I have created a jar file of my application so that users can run it from Windows Explorer. It loads a JSON file in its own working directory for some settings (using the path ".\config.json"). However, when I run it from the jar file from Windows Explorer, it cannot find the config file, while running the same jar from the command line works. I'm assuming this is because explorer sets the working directory to something other than the jar's folder. What does it set it to? (And how can I find the jar's own folder?)

bluish
  • 26,356
  • 27
  • 122
  • 180
Orange
  • 51
  • 1
  • 2
  • If you can modify this jar you could pring current dir using this: http://www.java-forums.org/new-java/434-how-can-i-get-current-directory.html and check – dbf Nov 18 '11 at 20:05

2 Answers2

3

Why not try printing out System.getProperty("user.dir"); and finding out what the application thinks?

user.dir    User's current working directory

use the following to get the PARENT of where you .jar is loading from, which is what it sounds like you want

import java.io.*;

public class Main
{
    public static void main(final String[] args) throws IOException
    {
        final File file = new File(".");
        System.out.println("file = " + file.getAbsoluteFile().getParent());
    }
}

The output when I run it from the command line or double clicking from Windows Explorer is:

file = c:\Users\Jarrod Roberson\Projects\SwingJarFinder
bluish
  • 26,356
  • 27
  • 122
  • 180
0

Looks like a duplicate of:

How to get the path of a running JAR file?

If your jar file is in your file system start here to get the current path:

ClassLoader.getSystemClassLoader().getResource(".").getPath();
Community
  • 1
  • 1
Abdullah Jibaly
  • 53,220
  • 42
  • 124
  • 197
  • this doesn't return the path to the .jar but the path to the resource, which needs to be further processed to get the file path. Also this will not work if the classes are loaded from somewhere other than a file system. The file he wants isn't in the `.jar` but along side it! –  Nov 18 '11 at 21:26
  • Actually the code you posted throws `NullPointerException` with the `"."` in `.getResource()` –  Nov 19 '11 at 14:26
  • Nope, works for me I tested it on Mac OS Lion (JDK 1.6) and Windows 7 (JDK 1.7), no NullPointerException and gave me the correct path to the jar file. – Abdullah Jibaly Nov 19 '11 at 22:42
  • 1
    On Windows 7 JDK 1.6 it throws a `NullPointerException` when launched from command line and from Explorer and when launched from inside IntelliJ as well. –  Nov 20 '11 at 00:09
  • Strange, maybe something wrong with how you create the jar? Try the one I tested: http://temp-share.com/show/gFHKd9f6Y – Abdullah Jibaly Nov 20 '11 at 21:50
  • Just installed JDK 1.6 on Windows 7 and that works as well. Not sure what's wrong with your environment, maybe classpath issues? – Abdullah Jibaly Nov 20 '11 at 22:54