getResource使用java 1.7 windows 7在磁盘名称前面/前面

Jon*_*ale 16 java getresource

以下是磁盘名称前面的前导斜杠.我怎么能避免这种情况?

String pngpath = getClass().getResource("/resources/lena.png").getPath();
System.out.println("pngpath = "+pngpath);
Run Code Online (Sandbox Code Playgroud)

得到:

pngpath = /C:/Users/jgrimsdale/Documents/NetBeansProjects/HelloCV/build/classes/resources/lena.png
Run Code Online (Sandbox Code Playgroud)

Dio*_*ana 24

使用:

String pngpath = getClass().getResource("/resources/lena.png").getFile();
File file = new File(pngpath);
System.out.println(file.getAbsolutePath());
Run Code Online (Sandbox Code Playgroud)


Bis*_*jit -1

您可以使用此代码来完成此操作。

System.out.println("pngpath = "+pngpath.substring(1,pngpath.length()));
Run Code Online (Sandbox Code Playgroud)

  • 这会在 Linux 上产生一个 filenotfound ,其中前导斜杠是必需的。@diogosantana 的答案更加独立于平台 (4认同)