我的代码在一个JAR文件中运行,比如foo.jar,我需要知道,在代码中,运行的foo.jar在哪个文件夹中。
所以,如果FOO .jar在C:\FOO\中,无论我当前的工作目录是什么,我都想获得这个路径。
我的代码在一个JAR文件中运行,比如foo.jar,我需要知道,在代码中,运行的foo.jar在哪个文件夹中。
所以,如果FOO .jar在C:\FOO\中,无论我当前的工作目录是什么,我都想获得这个路径。
当前回答
对我来说,在Linux、Mac和Windows上都适用的唯一解决方案是:
public static String getJarContainingFolder(Class aclass) throws Exception {
CodeSource codeSource = aclass.getProtectionDomain().getCodeSource();
File jarFile;
if (codeSource.getLocation() != null) {
jarFile = new File(codeSource.getLocation().toURI());
}
else {
String path = aclass.getResource(aclass.getSimpleName() + ".class").getPath();
String jarFilePath = path.substring(path.indexOf(":") + 1, path.indexOf("!"));
jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8");
jarFile = new File(jarFilePath);
}
return jarFile.getParentFile().getAbsolutePath();
}
其他回答
如果您确实在寻找一种获取JAR所在文件夹的简单方法,那么您应该使用这个实现。 像这样的解决方案很难找到,许多解决方案不再受支持,许多其他解决方案提供文件的路径,而不是实际的目录。这比您将要找到的其他解决方案更容易,并且适用于java版本1.12。
new File(".").getCanonicalPath()
从其他答案中收集输入,这也是一个简单的答案:
String localPath=new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).getParentFile().getPath()+"\\";
两者都会返回如下格式的String:
"C:\Users\User\Desktop\Folder\"
用简洁明了的线条。
这里是其他评论的升级版,在我看来,这些评论的细节并不完整
在.jar文件外使用一个相对的“文件夹”(在jar的相同 位置):
String path =
YourMainClassName.class.getProtectionDomain().
getCodeSource().getLocation().getPath();
path =
URLDecoder.decode(
path,
"UTF-8");
BufferedImage img =
ImageIO.read(
new File((
new File(path).getParentFile().getPath()) +
File.separator +
"folder" +
File.separator +
"yourfile.jpg"));
public static String dir() throws URISyntaxException
{
URI path=Main.class.getProtectionDomain().getCodeSource().getLocation().toURI();
String name= Main.class.getPackage().getName()+".jar";
String path2 = path.getRawPath();
path2=path2.substring(1);
if (path2.contains(".jar"))
{
path2=path2.replace(name, "");
}
return path2;}
在Windows上运行良好
如果你从Gnome桌面环境(不是任何脚本或终端)点击运行jar,上面所选的答案是不工作的。
相反,我认为下面的解决方案在任何地方都适用:
try {
return URLDecoder.decode(ClassLoader.getSystemClassLoader().getResource(".").getPath(), "UTF-8");
} catch (UnsupportedEncodingException e) {
return "";
}
我有另一种方法来获取类的String位置。
URL path = Thread.currentThread().getContextClassLoader().getResource("");
Path p = Paths.get(path.toURI());
String location = p.toString();
输出字符串的形式为
C:\Users\Administrator\new Workspace\...
空格和其他字符被处理,并且在没有file:/的形式。这样会更容易使用。