可以使用以下代码来获取当前jar包的上一级目录:
File jarFile =new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
File jarDir = jarFile.getParentFile();
其中,Main.class
是当前类的类对象。这段代码先使用 getProtectionDomain().getCodeSource().getLocation().toURI().getPath()
获取当前jar文件的路径,然后使用 File
类的 getParentFile()
方法获取上一级目录。
注意,如果当前程序不是运行在jar文件中,则该方法可能会无效。