我的代码在一个JAR文件中运行,比如foo.jar,我需要知道,在代码中,运行的foo.jar在哪个文件夹中。
所以,如果FOO .jar在C:\FOO\中,无论我当前的工作目录是什么,我都想获得这个路径。
我的代码在一个JAR文件中运行,比如foo.jar,我需要知道,在代码中,运行的foo.jar在哪个文件夹中。
所以,如果FOO .jar在C:\FOO\中,无论我当前的工作目录是什么,我都想获得这个路径。
当前回答
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
.toURI()).getPath();
将“MyClass”替换为类名。
显然,如果您的类是从非文件位置加载的,这将会做一些奇怪的事情。
其他回答
我有另一种方法来获取类的String位置。
URL path = Thread.currentThread().getContextClassLoader().getResource("");
Path p = Paths.get(path.toURI());
String location = p.toString();
输出字符串的形式为
C:\Users\Administrator\new Workspace\...
空格和其他字符被处理,并且在没有file:/的形式。这样会更容易使用。
使用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教程。
其他答案似乎指向的代码源是Jar文件的位置,而不是一个目录。
Use
return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath()).getParentFile();
令人沮丧的是,当您在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");
}
对于一些愚蠢的简单的东西,你只需要这一行:
对于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();
}