1

I have an executable jar file and I want it to be able to read and write info to a txt file that is located at the same dir as the .jar file is. How can I do that? How can I get the executable jar file dir path. It only has to work on windows platform and it's a desktop application.

Karuvägistaja
  • 293
  • 1
  • 8
  • 17
  • 4
    http://stackoverflow.com/questions/320542/how-to-get-the-path-of-a-running-jar-file –  Jun 16 '12 at 17:43

4 Answers4

1

You don't need to specify full path in order to create new files, java will create new files in current working directory by default.

Ehsan Khodarahmi
  • 4,772
  • 10
  • 60
  • 87
1

I have an executable jar file and I want it to be able to read and write info to a txt file that is located at the same dir as the .jar file is.

Don't do that! Most OS makers have long been saying not to put applications and application data in the same place. The best place for application data is a sub-directory of user.home.

E.G.

import java.io.File;

public class QuickTest {

    public static void main(String[] args) {
        String[] pkgPath = { "com", "our", "app" };
        File f = new File(System.getProperty("user.home"));
        File subDir = f;
        for (String pkg : pkgPath) {
            subDir = new File(subDir,pkg);
        }
        System.out.println(f.getAbsoluteFile());
        System.out.println(subDir.getAbsoluteFile());
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
1

Class.getProtectionDomain().getCodeSource().getLocation() will return the location of the JAR that contains the class you called it on, if it's in a JAR.

However see also Andrew Thompson's answer.

user207421
  • 305,947
  • 44
  • 307
  • 483
1

The following code snippet will do this for you:

final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());

replace MyClass with your main class

The resulting File object f represents the .jar file that was executed. You can use this object to get the directory the file is in and use that to build a directory path.