getResource puts a leading / before the disk name using java 1.7 windows 7
Asked Answered
L

3

25

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
Libau answered 27/3, 2013 at 15:32 Comment(4)
What happens when you remove the leading slash from your getResource statement?Chilly
I believe that path is still valid, even with the leading /.Klara
@SotiriosDelimanolis Not in certain contexts it isn't.Unhesitating
@SotiriosDelimanolis Apparently not in Java NIO's getPath() https://mcmap.net/q/331161/-java-nio-file-path-issueProtecting
S
36

Use:

String pngpath = getClass().getResource("/resources/image.png").getFile();
File file = new File(pngpath);
System.out.println(file.getAbsolutePath());
Sulfapyridine answered 27/3, 2013 at 15:55 Comment(0)
L
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)

Lycaonia answered 4/3, 2017 at 9:40 Comment(0)
C
-1

you can do this using this code.

System.out.println("pngpath = "+pngpath.substring(1,pngpath.length()));
Cataplasm answered 27/3, 2013 at 15:49 Comment(1)
this would yield a filenotfound on linux where the leading slash is necessary. @diogosantana 's answer is more platform independantWhiny

© 2022 - 2024 — McMap. All rights reserved.