How to know the directory of jar file in java? [duplicate]

旧时模样 提交于 2019-12-08 06:26:13

问题


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.


回答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.




回答2:


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());
    }
}



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/11065637/how-to-know-the-directory-of-jar-file-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!