21

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
Dave Jarvis
  • 29,586
  • 38
  • 176
  • 304
Jonathan Grimsdale
  • 211
  • 1
  • 2
  • 3

3 Answers3

32

Use:

String pngpath = getClass().getResource("/resources/image.png").getFile();
File file = new File(pngpath);
System.out.println(file.getAbsolutePath());
Dave Jarvis
  • 29,586
  • 38
  • 176
  • 304
DiogoSantana
  • 2,356
  • 1
  • 18
  • 23
1

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)

-1

you can do this using this code.

System.out.println("pngpath = "+pngpath.substring(1,pngpath.length()));
Biswajit
  • 2,376
  • 2
  • 25
  • 35
  • 4
    this would yield a filenotfound on linux where the leading slash is necessary. @diogosantana 's answer is more platform independant – s.ijpma Aug 11 '15 at 13:35