我的代码在一个JAR文件中运行,比如foo.jar,我需要知道,在代码中,运行的foo.jar在哪个文件夹中。
所以,如果FOO .jar在C:\FOO\中,无论我当前的工作目录是什么,我都想获得这个路径。
我的代码在一个JAR文件中运行,比如foo.jar,我需要知道,在代码中,运行的foo.jar在哪个文件夹中。
所以,如果FOO .jar在C:\FOO\中,无论我当前的工作目录是什么,我都想获得这个路径。
当前回答
getProtectionDomain方法有时可能不起作用,例如当你必须为一些核心java类(例如在我的情况下,IBM JDK中的StringBuilder类)找到jar时,但是下面的工作是无缝的:
public static void main(String[] args) {
System.out.println(findSource(MyClass.class));
// OR
System.out.println(findSource(String.class));
}
public static String findSource(Class<?> clazz) {
String resourceToSearch = '/' + clazz.getName().replace(".", "/") + ".class";
java.net.URL location = clazz.getResource(resourceToSearch);
String sourcePath = location.getPath();
// Optional, Remove junk
return sourcePath.replace("file:", "").replace("!" + resourceToSearch, "");
}
其他回答
我试图让罐子运行路径使用
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 = new File("").getAbsolutePath();
对于jar文件路径:
String jarPath = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getPath();
获取jar文件的目录路径:
String dirPath = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getParent();
上面两行的结果是这样的:
/home/user/MyPrograms/myapp/myjar.jar (jarPath的值)
/home/user/MyPrograms/myapp (dirPath的值)
这个方法从存档中的代码中调用,返回.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运行
其他答案似乎指向的代码源是Jar文件的位置,而不是一个目录。
Use
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile();