getResource puts a leading / before the disk name

2019-04-19 07:24发布

The following gives a leading slash before the disk name. How can I avoid that?

String pngpath = getClass().getResource("/resources/lena.png").getPath();
System.out.println("pngpath = "+pngpath);

Gives:

pngpath = /C:/Users/jgrimsdale/Documents/NetBeansProjects/HelloCV/build/classes/resources/lena.png

3条回答
我只想做你的唯一
2楼-- · 2019-04-19 07:36

Use:

String pngpath = getClass().getResource("/resources/lena.png").getFile();
File file = new File(pngpath);
System.out.println(file.getAbsolutePath());
查看更多
乱世女痞
3楼-- · 2019-04-19 07:37

you can do this using this code.

System.out.println("pngpath = "+pngpath.substring(1,pngpath.length()));
查看更多
地球回转人心会变
4楼-- · 2019-04-19 07:50

A constructor of File(uri) or File(string) helps to get file object from system dependent path string or URI object.

It is a solution to using the Java Library.

System.out.println(new File("/C:/Users/jgrimsdale").toString())

https://docs.oracle.com/javase/7/docs/api/java/io/File.html#File(java.net.URI)

查看更多
登录 后发表回答