如何摆脱URI或URL中的起始斜杠?

Ev0*_*0oD 7 url uri path absolute-path

我在用

URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
String path = res.getPath();
String path2 = path.substring(1);
Run Code Online (Sandbox Code Playgroud)

因为方法getPath()的输出返回sth,如下所示:

 /C:/Users/......
Run Code Online (Sandbox Code Playgroud)

我需要这个

 C:/Users....
Run Code Online (Sandbox Code Playgroud)

我真的需要以下地址,因为一些外部库拒绝在开头使用斜杠或使用file:/开头或其他任何东西.

我在URL中尝试了几乎所有的方法,比如toString()toExternalPath()等,并且使用URI完成相同的操作,并且没有一个像我需要的那样返回它.(我完全不明白,为什么它在开头保留斜线).

只需擦除第一个字符就可以在我的机器上完成.但是一位朋友试图在linux上运行它,因为那里的地址不同,它不起作用......

应该有这样的问题?

Sun*_*dae 7

将URL转换为URI并在File构造函数中使用它:

URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
File file = new File(res.toURI());
String fileName = file.getPath();
Run Code Online (Sandbox Code Playgroud)


Dav*_*shi 4

只要 UNIX 路径不应包含驱动器号,您就可以尝试以下操作:

URL res = this.getClass().getClassLoader().getResource(dictionaryPath);
String path = res.getPath();
char a_char = text.charAt(2);
if (a_char==':') path = path.substring(1);
Run Code Online (Sandbox Code Playgroud)