我有一种情况,我需要扫描运行时类路径以查找资源文件(例如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 个侧面。有没有更好/更容易/更优雅的方式来做到这一点?提前致谢!