我的代码在一个JAR文件中运行,比如foo.jar,我需要知道,在代码中,运行的foo.jar在哪个文件夹中。
所以,如果FOO .jar在C:\FOO\中,无论我当前的工作目录是什么,我都想获得这个路径。
我的代码在一个JAR文件中运行,比如foo.jar,我需要知道,在代码中,运行的foo.jar在哪个文件夹中。
所以,如果FOO .jar在C:\FOO\中,无论我当前的工作目录是什么,我都想获得这个路径。
当前回答
如果您确实在寻找一种获取JAR所在文件夹的简单方法,那么您应该使用这个实现。 像这样的解决方案很难找到,许多解决方案不再受支持,许多其他解决方案提供文件的路径,而不是实际的目录。这比您将要找到的其他解决方案更容易,并且适用于java版本1.12。
new File(".").getCanonicalPath()
从其他答案中收集输入,这也是一个简单的答案:
String localPath=new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).getParentFile().getPath()+"\\";
两者都会返回如下格式的String:
"C:\Users\User\Desktop\Folder\"
用简洁明了的线条。
其他回答
String path = getClass().getResource("").getPath();
路径总是引用jar文件中的资源。
我已经尝试了上面的几种解决方案,但是对于在Eclipse中使用“打包外部库”导出可运行jar的情况(可能是特殊情况),没有一个产生正确的结果。出于某种原因,所有基于ProtectionDomain的解决方案在这种情况下都将导致null。
通过结合上面的一些解决方案,我成功地实现了以下工作代码:
String surroundingJar = null;
// gets the path to the jar file if it exists; or the "bin" directory if calling from Eclipse
String jarDir = new File(ClassLoader.getSystemClassLoader().getResource(".").getPath()).getAbsolutePath();
// gets the "bin" directory if calling from eclipse or the name of the .jar file alone (without its path)
String jarFileFromSys = System.getProperty("java.class.path").split(";")[0];
// If both are equal that means it is running from an IDE like Eclipse
if (jarFileFromSys.equals(jarDir))
{
System.out.println("RUNNING FROM IDE!");
// The path to the jar is the "bin" directory in that case because there is no actual .jar file.
surroundingJar = jarDir;
}
else
{
// Combining the path and the name of the .jar file to achieve the final result
surroundingJar = jarDir + jarFileFromSys.substring(1);
}
System.out.println("JAR File: " + surroundingJar);
我试图让罐子运行路径使用
String folder = MyClassName.class.getProtectionDomain().getCodeSource().getLocation().getPath();
C:\app>java -jar application.jar
运行名为“application.jar”的jar应用程序,在Windows文件夹“c:\app”中,字符串变量“文件夹”的值是“\c:\app\application.jar”,我在测试路径的正确性时遇到了问题
File test = new File(folder);
if(file.isDirectory() && file.canRead()) { //always false }
所以我试着将“test”定义为:
String fold= new File(folder).getParentFile().getPath()
File test = new File(fold);
以正确的格式获取路径,如“c:\app”而不是“\c:\app\application.jar”,我注意到它是有效的。
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getPath();
将“MyClass”替换为类名。
显然,如果您的类是从非文件位置加载的,这将会做一些奇怪的事情。
我用Java 7编写,用Oracle的运行时在Windows 7上测试,用开源运行时在Ubuntu上测试。这对于这些系统来说是完美的:
任何正在运行的jar文件的父目录的路径(假设调用这段代码的类是jar存档本身的直接子目录):
try {
fooDir = new File(this.getClass().getClassLoader().getResource("").toURI());
} catch (URISyntaxException e) {
//may be sloppy, but don't really need anything here
}
fooDirPath = fooDir.toString(); // converts abstract (absolute) path to a String
因此,foo.jar的路径是:
fooPath = fooDirPath + File.separator + "foo.jar";
同样,这也没有在任何Mac或旧版本的Windows上进行测试