Java 如何以字节数组为参数构建 FileInputStream 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19829955/
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
How to build FileInputStream object with byte array as a parameter
提问by Rauf
I have a zip file and after decoding it I get a byte array now I want to create a FileInputStream object with that byte[] object. I dont want to create a file instead pass data content do FileInputStream. Is there any way ?
我有一个 zip 文件,解码后得到一个字节数组,现在我想用那个 byte[] 对象创建一个 FileInputStream 对象。我不想创建一个文件而是通过数据内容做 FileInputStream。有什么办法吗?
following is the code:
以下是代码:
byte[] decodedHeaderFileZip = decodeHeaderZipFile(headerExportFile);
FileInputStream fileInputStream = new FileInputStream(decodedHeaderZipFileString);
EDIT: I wanted to build a ZipInputStream object with a FileInputStream.
编辑:我想用 FileInputStream 构建一个 ZipInputStream 对象。
采纳答案by Jon Skeet
I have a zip file and after decoding it I get a byte array now I want to create a FileInputStream object with that byte[] object.
我有一个 zip 文件,解码后得到一个字节数组,现在我想用那个 byte[] 对象创建一个 FileInputStream 对象。
But you don't have a file. You have some data in memory. So a FileInputStream
is inappropriate - there's no file for it to read from.
但是你没有文件。您的内存中有一些数据。所以 aFileInputStream
是不合适的 - 没有可供它读取的文件。
If possible, use a ByteArrayInputStream
instead:
如果可能,请改用 a ByteArrayInputStream
:
InputStream input = new ByteArrayInputStream(decodedHeaderFileZip);
Where possible, express your API in terms of InputStream
, Reader
etc rather than any specific implementation - that allows you to be flexible in which implementation you use. (What I mean is that where possible, make method parameters and return types InputStream
rather than FileInputStream
- so that callers don't need to provide the specific types.)
在可能的情况下InputStream
,用Reader
等来表达您的 API ,而不是任何特定的实现 - 这使您可以灵活地使用您使用的实现。(我的意思是,在可能的情况下,制作方法参数和返回类型InputStream
而不是FileInputStream
- 这样调用者就不需要提供特定类型。)
If you absolutely haveto create a FileInputStream
, you'll need to write the data to a file first.
如果您绝对必须创建一个FileInputStream
,则需要先将数据写入文件。