我的代码在一个JAR文件中运行,比如foo.jar,我需要知道,在代码中,运行的foo.jar在哪个文件夹中。
所以,如果FOO .jar在C:\FOO\中,无论我当前的工作目录是什么,我都想获得这个路径。
我的代码在一个JAR文件中运行,比如foo.jar,我需要知道,在代码中,运行的foo.jar在哪个文件夹中。
所以,如果FOO .jar在C:\FOO\中,无论我当前的工作目录是什么,我都想获得这个路径。
当前回答
对我来说最好的解决方案:
String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
这应该可以解决空格和特殊字符的问题。
其他回答
使用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教程。
我很惊讶地发现,最近没有人建议使用Path。以下是引用:“Path类包括各种方法,可用于获取路径信息、访问路径元素、将路径转换为其他形式或提取路径的部分”
因此,一个好的替代方法是获取Path对象为:
Path path = Paths.get(Test.class.getProtectionDomain().getCodeSource().getLocation().toURI());
在我最终找到一个有效(且简短)的解决方案之前,我不得不浪费很多时间。 有可能jarLocation带有一个像file:\或jar:file\这样的前缀,可以使用String#substring()来删除。
URL jarLocationUrl = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
String jarLocation = new File(jarLocationUrl.toString()).getParent();
不太确定其他人,但在我的情况下,它不与“可运行的罐子”,我得到了它的工作通过修复代码一起从phchen2答案和另一个从这个链接:如何获得一个运行的jar文件的路径? 代码:
String path=new java.io.File(Server.class.getProtectionDomain()
.getCodeSource()
.getLocation()
.getPath())
.getAbsolutePath();
path=path.substring(0, path.lastIndexOf("."));
path=path+System.getProperty("java.class.path");
对于一些愚蠢的简单的东西,你只需要这一行:
对于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();
}