2016-09-24 514 views
2

我有两个方法来获取罐路径如何在Linux中使用java命令获取当前正在执行的jar包的空间路径?

1)

File file = new File(new File(Main.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName()); 
String filename = file.getAbsolutePath().toString(); 

2)

String filename2 = Main.class.getProtectionDomain().getCodeSource().getLocation().toString().substring(6); 

第一种方法完全适用于Windows和Mac,但在Linux上,如果我的罐子如果我的终端位于/home/user/,即使MyJar.jar路径为'/home/user/Documents/test folder/',也会返回/home/user/MyJar.jar

对于每个操作系统,第二种方法将返回到文件的正确路径,但空格替换为%20。

例:/home/user/Documents/test%20folder/MyJar.jar

我怎样才能获得在Linux中的绝对路径以同样的方式我为Windows和Mac做的,没有20%的空间置换?

+0

如果第二个最适合你和你只是担心' %20',那么你可以简单地添加'.replace(“%20”,“”)'来替换所有的空格! – user2004685

+0

更好地解码jar的位置,而不是手动将%20替换为空格 – Naruto

+0

我不知道这是解决该问题的解决方法,但“java.net.url.URLDecoder.decode”怎么办? – engineercoding

回答

2

我不确定为什么你在第一个解决方案中将你的File重叠了一倍。

try { 
    File f = new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI()); 
    System.out.println(f.getAbsolutePath()); 
} catch (URISyntaxException ex) { 
    throw new RuntimeException(ex); 
} 

(仅在Linux下测试)

(我不认为的URISyntaxException将永远在生产中抛出)

+0

都是如此,但实际上并没有解决问题。 – EJP

+0

我的代码给出了调用jar文件的绝对路径,不管它是否包含空格。我不明白它不能解决问题。 –

+0

谢谢,它对我来说非常合适。 –

相关问题