1

I know that the system property "user.dir" returns the current working directory; the directory containing that file that is currently running.

I am wondering, how would I be able to go one step farther? I need to find the current working file. I am writing a little app that is kind of like an auto-updater, and I need to know the file that needs to be updated. For example, if I run a file from C:/test.jar I want to actually know, in code, that the current location of the file that is running is C:/test.jar so that I can write (new) data to it.

I've tried an approach like this:

    ClassLoader loader = Test.class.getClassLoader();
    System.out.println(loader.getResource("Test.class"));

However, it prints out:

3/5/12 7:50:16.914 PM [0x0-0x31031].com.apple.JarLauncher: rsrc:Test.class

(I am running this on a Mac - I got that line from the Console). Any help is greatly appreciated. Thanks!

Martin Tuskevicius
  • 2,590
  • 4
  • 29
  • 46

2 Answers2

3

With credits to Fab in the following post: Jar path+name from currently running jar

String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
Community
  • 1
  • 1
JScoobyCed
  • 10,203
  • 6
  • 34
  • 58
0

This will print the current file's path.

File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
        System.out.println(f.getPath());
John Eipe
  • 10,922
  • 24
  • 72
  • 114