以文件访问Java资源 [英] Accessing a Java Resource as a File

查看:60
本文介绍了以文件访问Java资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从类路径/JAR文件作为File对象访问资源.我知道这是代替使用InputStream对象的首选方法,但是我正在使用需要File对象的外部库(WorldEdit).

I'm trying to access a resource from the class path/JAR file as a File object. I'm aware that it's the preferred method to use an InputStream object instead, but I'm using an external library (WorldEdit) which needs a File object.

这是我的代码:

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());

现在,当我仍处于日食状态时,两种访问资源的方式都可以正常工作并产生以下输出:

Now while I'm still inside eclipse, both ways of accessing the resource work flawlessly and produce this output:

templStream: java.io.BufferedInputStream@746d1683
templFile: true

但是将代码导出到JAR归档文件后,代码将失败:

But after exporting the code into a JAR archive, the code fails:

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转换为文件的方法.

So I've been, without success, searching for a way for either accessing the resource as a File directly, or going the way of using an InputStream and converting that InputStream to a file.

最糟糕的后备解决方案是将InputStream复制到文件系统上的文件,然后打开该文件,但我希望这不是必需的.

The worst case fallback solution would be to copy the InputStream to a file on the filesystem, and then open that file, but I hope that won't be neccesary.

推荐答案

简短的答案是您不能,因为资源不是文件.

The short answer is that you can't, because the resource isn't a File.

如果第三方库想要做的只是从源中读取数据(因此它应该使用InputStream),或者第三方库实际上想进行特定于文件的操作,要么写得不好.

Either the third-party library is badly written if all it wants to do is read data from a source (and thus it should take an InputStream), or the library actually wants to do File-specific manipulations.

假设这不是可以修复的库中的疏忽,则需要实际创建一个文件.尝试调用File.createTempFile(),自己用资源的内容填充此文件,然后将此File对象传递给库. (当然,一旦完成,请删除它.)

Assuming this isn't an oversight in the library that can be fixed, you'll need to actually create a file yourself. Try calling File.createTempFile(), populate this file with the contents of the resource yourself, and then pass this File object to the library. (Delete it once you're done, of course).

这篇关于以文件访问Java资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆