我的代码在一个JAR文件中运行,比如foo.jar,我需要知道,在代码中,运行的foo.jar在哪个文件夹中。
所以,如果FOO .jar在C:\FOO\中,无论我当前的工作目录是什么,我都想获得这个路径。
我的代码在一个JAR文件中运行,比如foo.jar,我需要知道,在代码中,运行的foo.jar在哪个文件夹中。
所以,如果FOO .jar在C:\FOO\中,无论我当前的工作目录是什么,我都想获得这个路径。
当前回答
对于一些愚蠢的简单的东西,你只需要这一行:
对于Windows用户,将“pwd”更改为“cd”
runCommand("pwd");
然后把这个方法扔到类中:
public static String runCommand(String command) {
StringBuilder sb = new StringBuilder();
try {
ProcessBuilder pb = new ProcessBuilder(command);
final Process p = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
sb.append(br.read());
while ((line= br.readLine()) != null) sb.append(line).append("\n");
}
catch (IOException e) {e.printStackTrace();}
return sb.toString();
}
其他回答
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getPath();
将“MyClass”替换为类名。
显然,如果您的类是从非文件位置加载的,这将会做一些奇怪的事情。
对我来说最好的解决方案:
String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
这应该可以解决空格和特殊字符的问题。
为了获得运行jar文件的路径,我研究了上述解决方案,并尝试了各种方法,它们之间存在一些差异。如果这些代码在Eclipse IDE中运行,它们都应该能够找到包含指定类的文件路径,并使用找到的路径打开或创建指定的文件。
但这很棘手,当直接或通过命令行运行可运行的jar文件时,它将失败,因为从上述方法获得的jar文件的路径将在jar文件中给出一个内部路径,也就是说它总是给出一个路径
rsrc:project-name(也许我应该说它是主类文件的包名-指定的类)
我不能转换rsrc:…路径到外部路径,即当在Eclipse IDE外部运行jar文件时,无法获得jar文件的路径。
在Eclipse IDE之外获取运行jar文件的路径的唯一可能方法是
System.getProperty("java.class.path")
这段代码行可能返回的生活路径(包括文件名)运行jar文件(注意,返回路径不是工作目录),作为java文档,有些人说,它将返回所有类文件在同一个目录的路径,但随着我的测试中,如果在相同的目录中包括许多jar文件,它只返回运行jar的路径(约多条路径问题确实发生在Eclipse)。
我也遇到过同样的问题,我是这样解决的:
File currentJavaJarFile = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath());
String currentJavaJarFilePath = currentJavaJarFile.getAbsolutePath();
String currentRootDirectoryPath = currentJavaJarFilePath.replace(currentJavaJarFile.getName(), "");
希望我能对你有所帮助。
使用ClassLoader.getResource()来查找当前类的URL。
例如:
package foo;
public class Test
{
public static void main(String[] args)
{
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader.getResource("foo/Test.class"));
}
}
(这个例子来自一个类似的问题。)
要找到该目录,需要手动分解URL。有关jar URL的格式,请参阅JarClassLoader教程。