20

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

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

Gives:

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

3 回答 3

32

Use:

String pngpath = getClass().getResource("/resources/image.png").getFile();
File file = new File(pngpath);
System.out.println(file.getAbsolutePath());
于 2013-03-27T15:55:01.870 回答
1

File(uri) 或 File(string) 的构造函数有助于从系统相关的路径字符串或 URI 对象中获取文件对象。

它是使用 Java 库的解决方案。

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)

于 2017-03-04T09:40:10.507 回答
-1

您可以使用此代码执行此操作。

System.out.println("pngpath = "+pngpath.substring(1,pngpath.length()));
于 2013-03-27T15:49:27.770 回答