0

我有一种情况,我需要扫描运行时类路径以查找资源文件(例如res/config/meta.cfg),然后为其创建File句柄。我能想到的最好的是:

// This file is located inside a JAR that is on the runtime classpath.
String fileName = "res/config/meta.cfg";

try {
    InputStream inStream = ClassLoader.getSystemResourceAsStream(fileName);
    File file = new File(String.format("${java.io.tmpdir}/%s", fileName));
    FileOutputStream foutStream = null;
    foutStream = new FileOutputStream(file);

    int read = 0;
    byte[] bytes = new byte[1024];
    while((read = inStream.read(bytes)) != -1)
        foutStream.write(bytes, 0, read);

    foutStream.close();

    return file;
} catch (Exception exc) {
    throw new RuntimeException(exc);
}

因此,本质上,将资源作为 读入InputStream,然后将流写入临时文件(在 下{$java.io.tmpdir}),以便我们可以获得File它的有效句柄。

这似乎是围绕谷仓的 3 个侧面。有没有更好/更容易/更优雅的方式来做到这一点?提前致谢!

4

1 回答 1

2

不。

当然,您可以(并且可能应该)使用库将 's 的内容复制InputStream文件中,但这显然不是您问题的重点。

类路径不仅仅包含目录;资源可以在档案(通常是 JAR)或服务器上,并且可能不作为可以通过java.io.File对象访问的东西存在。

通常,核心问题是在足够java.io.File的情况下使用对象。InputStream有时在使用第三方库时您无法对它采取任何措施,但这表明库设计者工作不够仔细。如果您在自己的代码中需要文件句柄,您应该再看看为什么它不能是InputStream. 大多数时候可以。

于 2013-09-24T11:19:19.637 回答