我的代码在一个JAR文件中运行,比如foo.jar,我需要知道,在代码中,运行的foo.jar在哪个文件夹中。
所以,如果FOO .jar在C:\FOO\中,无论我当前的工作目录是什么,我都想获得这个路径。
我的代码在一个JAR文件中运行,比如foo.jar,我需要知道,在代码中,运行的foo.jar在哪个文件夹中。
所以,如果FOO .jar在C:\FOO\中,无论我当前的工作目录是什么,我都想获得这个路径。
当前回答
我试图让罐子运行路径使用
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”,我注意到它是有效的。
其他回答
String path = getClass().getResource("").getPath();
路径总是引用jar文件中的资源。
这个方法从存档中的代码中调用,返回.jar文件所在的文件夹。它应该在Windows或Unix中工作。
private String getJarFolder() {
String name = this.getClass().getName().replace('.', '/');
String s = this.getClass().getResource("/" + name + ".class").toString();
s = s.replace('/', File.separatorChar);
s = s.substring(0, s.indexOf(".jar")+4);
s = s.substring(s.lastIndexOf(':')-1);
return s.substring(0, s.lastIndexOf(File.separatorChar)+1);
}
从下面的代码派生:确定是否从JAR运行
令人沮丧的是,当您在Eclipse中进行开发时,MyClass.class.getProtectionDomain(). getcodesource (). getlocation()返回/bin目录,这很好,但当您将其编译到jar时,该路径包括/myjarname.jar部分,这为您提供了非法的文件名。
为了让代码既能在ide中工作,又能编译到jar中,我使用了下面这段代码:
URL applicationRootPathURL = getClass().getProtectionDomain().getCodeSource().getLocation();
File applicationRootPath = new File(applicationRootPathURL.getPath());
File myFile;
if(applicationRootPath.isDirectory()){
myFile = new File(applicationRootPath, "filename");
}
else{
myFile = new File(applicationRootPath.getParentFile(), "filename");
}
如果您确实在寻找一种获取JAR所在文件夹的简单方法,那么您应该使用这个实现。 像这样的解决方案很难找到,许多解决方案不再受支持,许多其他解决方案提供文件的路径,而不是实际的目录。这比您将要找到的其他解决方案更容易,并且适用于java版本1.12。
new File(".").getCanonicalPath()
从其他答案中收集输入,这也是一个简单的答案:
String localPath=new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).getParentFile().getPath()+"\\";
两者都会返回如下格式的String:
"C:\Users\User\Desktop\Folder\"
用简洁明了的线条。
我用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上进行测试