如何在Linux中使用java命令获取带有空格的路径到当前执行的jar ?

时间:2022-05-19 07:23:16

I have two methods to obtain the jar path

我有两种方法来获得jar路径。

1)

1)

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

2)

2)

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

The first method works perfectly for windows and Mac, but in linux, if my jar is located at '/home/user/Documents/test folder/', it returns my current working directory + the jar file

第一种方法对于windows和Mac都非常适用,但是在linux中,如果我的jar位于'/home/user/Documents/test folder/',它将返回我当前的工作目录+ jar文件

Ex: If my terminal is at /home/user/, it returns /home/user/MyJar.jar even though MyJar.jar path is '/home/user/Documents/test folder/'.

例句:如果我的终端在/home/user/,它会返回/home/ user/myjar。瓶子尽管MyJar。jar路径是'/home/user/Documents/test folder/'。

The second method, for every operational system returns the correct path to the file but with spaces replaced by %20.

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

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

例:/home/user/Documents/test % 20文件夹/ MyJar.jar

How can I get the absolute path in Linux the same way I do for windows and Mac, and without %20 as space replacement?

如何在Linux中获得与windows和Mac相同的绝对路径,而不使用%20作为空间替换?

1 个解决方案

#1


2  

I'm not sure why you've double wrapped your File's in the first solution.

我不知道你为什么把文件放在第一个解决方案中。

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

(Only tested under Linux)

(只在Linux上测试过)

(I don't think the URISyntaxException will ever be thrown in production)

(我不认为URISyntaxException会在生产中被抛出)

#1


2  

I'm not sure why you've double wrapped your File's in the first solution.

我不知道你为什么把文件放在第一个解决方案中。

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

(Only tested under Linux)

(只在Linux上测试过)

(I don't think the URISyntaxException will ever be thrown in production)

(我不认为URISyntaxException会在生产中被抛出)