问题 getResource使用java 1.7 windows 7在磁盘名称前面/前面


以下是磁盘名称前面的前导斜杠。 我怎么能避免这种情况?

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

得到:

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

12328
2018-03-27 15:32


起源

当您从中删除前导斜杠时会发生什么 getResource 声明? - nattyddubbs
我相信这条道路仍然有效,即使领先 /。 - Sotirios Delimanolis
@SotiriosDelimanolis不是在某些情况下它不是。 - b1nary.atr0phy
@SotiriosDelimanolis显然不在Java NIO的getPath()中 stackoverflow.com/questions/9834776/java-nio-file-path-issue - DLight


答案:


使用:

String pngpath = getClass().getResource("/resources/lena.png").getFile();
File file = new File(pngpath);
System.out.println(file.getAbsolutePath());

17
2018-03-27 15:55





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)


0
2018-03-04 09:40





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

System.out.println("pngpath = "+pngpath.substring(1,pngpath.length()));

-1
2018-03-27 15:49



这将在linux上产生一个filenotfound,其中需要前导斜杠。 @diogosantana的答案更加平台独立 - s.ijpma