java 将 InputStream 转换为 FileInputStream

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5355040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:45:25  来源:igfitidea点击:

Convert InputStream into FileInputStream

javaiostream

提问by user489041

I have read this post How to convert InputStream to FileInputStreamon converting a InputStream into a FileInputStream. However, the answer does not work if you are using a resource that is in a jar file. Is there another way to do it.

我已经阅读了这篇文章如何将 InputStream 转换为 FileInputStream将 InputStream 转换为 FileInputStream。但是,如果您使用的是 jar 文件中的资源,则答案不起作用。有没有其他方法可以做到。

I need to do this to get the FileChannelfrom a call to Object.class.getResourceAsStream(resourceName);

我需要这样做才能FileChannel从呼叫中获得 Object.class.getResourceAsStream(resourceName);

回答by Jon Skeet

You can't, without basically writing to a file. Unless there's a file, there can't be a FileInputStreamor a FileChannel. If at all possible, make sure your code is agnostic to the input source - design it in terms of InputStreamand ByteChannel(or whatever kind of channel is most appropriate).

你不能,基本上没有写入文件。除非有文件,否则不能有 aFileInputStreamFileChannel. 如果可能,请确保您的代码与输入源无关 - 根据InputStreamByteChannel(或任何最合适的通道)进行设计。

回答by Andy Thomas

From the InputStream returned by Class.getResourceAsStream(), you can make a Channel with Channels.newChannel( InputStream ).

从 Class.getResourceAsStream() 返回的 InputStream,您可以使用Channels.newChannel( InputStream )创建一个 Channel

This is not the FileChannel you requested, but it is still a Channel. Is it sufficient to meet your needs?

这不是您请求的 FileChannel,但它仍然是一个 Channel。是否足以满足您的需求?

回答by Mike Samuel

If you really need a file and you know that the resource is not inside a jar or loaded remotely, then you can use getResourceinstead.

如果您确实需要一个文件并且您知道该资源不在 jar 中或远程加载,那么您可以getResource改用。

URL resourceLocation = Object.class.getResource(resourcePath);
if (resourceLocation == null) { throw new FileNotFoundException(resourcePath); }
File myFile = new File(resourceLocation.toURI());

If you don't absolutely need a FileChannelor can't make assumptions about how your classpath is laid out, then Andy Thomas-Cramer's solution is probably the best.

如果您不是绝对需要FileChannel或无法对类路径的布局方式做出假设,那么 Andy Thomas-Cramer 的解决方案可能是最好的。