问题描述
我的程序中有这一行:
InputStream Resource_InputStream=this.getClass().getClassLoader().getResourceAsStream("Resource_Name");
但是我怎样才能从中获取 FileInputStream [Resource_InputStream] ?
But how can I get FileInputStream from it [Resource_InputStream] ?
推荐答案
使用 ClassLoader#getResource()
如果其 URI 表示有效的本地磁盘文件系统路径.
Use ClassLoader#getResource()
instead if its URI represents a valid local disk file system path.
URL resource = classLoader.getResource("resource.ext");
File file = new File(resource.toURI());
FileInputStream input = new FileInputStream(file);
// ...
如果没有(例如 JAR),那么最好的办法是将其复制到一个临时文件中.
If it doesn't (e.g. JAR), then your best bet is to copy it into a temporary file.
Path temp = Files.createTempFile("resource-", ".ext");
Files.copy(classLoader.getResourceAsStream("resource.ext"), temp, StandardCopyOption.REPLACE_EXISTING);
FileInputStream input = new FileInputStream(temp.toFile());
// ...
也就是说,我真的没有看到这样做的任何好处,或者它必须是一个需要 FileInputStream
而不是 InputStream
的糟糕帮助类/方法所需要的.如果可以,只需修复 API 以请求 InputStream
代替.如果是第 3 方,请务必将其报告为错误.在这种特定情况下,我还会在该 API 的其余部分周围加上问号.
That said, I really don't see any benefit of doing so, or it must be required by a poor helper class/method which requires FileInputStream
instead of InputStream
. If you can, just fix the API to ask for an InputStream
instead. If it's a 3rd party one, by all means report it as a bug. I'd in this specific case also put question marks around the remainder of that API.
这篇关于如何将 InputStream 转换为 FileInputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!