我正在尝试将类路径/JAR文件中的资源作为File对象访问。我知道使用InputStream对象是首选方法,但我正在使用一个需要File对象的外部库(WorldEdit)。
以下是我的代码:
InputStream templStream = "".getClass().getResourceAsStream("/res/template.prom");
System.out.println("templateStream: " + templStream.toString());
File templFile = new File("".getClass().getResource("/res/template.prom").toURI());
System.out.println("templateFile: " + templFile.canRead());
现在,当我仍然在eclipse中时,访问资源的两种方式都可以完美地工作,并产生以下输出:
templStream: java.io.BufferedInputStream@746d1683
templFile: true
但是当将代码导出为JAR档案后,代码会失败:
templStream: sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream@47aa261b
Exception in thread "main" java.lang.IllegalArgumentException: URI is not hierarchical
at java.io.File.<init>(File.java:392)
at SMCToPROM.main(SMCToPROM.java:101)
我一直在寻找一种方法,直接访问资源作为文件,或者使用InputStream并将其转换为文件,但是一直没有成功。
最坏的情况下,备选方案是将InputStream复制到文件系统中的文件,然后打开该文件,但希望不必这样做。