24

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
  • 30,436
  • 41
  • 178
  • 315
Jonathan Grimsdale
  • 241
  • 1
  • 2
  • 3

3 Answers3

35

Use:

String pngpath = getClass().getResource("/resources/image.png").getFile();
File file = new File(pngpath);
System.out.println(file.getAbsolutePath());
Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
DiogoSantana
  • 2,404
  • 2
  • 19
  • 24
2

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,434
  • 2
  • 28
  • 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