文件输出流到文件输入流
将 FileOutputStream 转换为 FileInputStream 的最简单方法是什么(一段代码就很好)?
What is the simplest way to convert a FileOutputStream into FileInputStream (a piece of code would be great)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这可能对您有帮助:
http://ostermiller.org/convert_java_outputstream_inputstream.html
本文提到了 3 种可能性
仅供参考,以相反的方式进行(输入到输出):
使用 Apache Commons IO 的一个简单解决方案是:
或者如果您只想复制文件:
如果您不想使用 Apache Commons IO,这是
copyLarge
方法的作用:This might help you:
http://ostermiller.org/convert_java_outputstream_inputstream.html
This article mentions 3 possibilities:
Just for reference, doing it the other way round (input to output):
A simple solution with Apache Commons IO would be:
or if you just want to copy a file:
If you don't want to use Apache Commons IO, here's what the
copyLarge
method does:您当然无法从
OutputStream
中读取。我认为您的意思是您想从 FileOutputStream 写入的文件中读取内容。我认为你也做不到。FileOutputStream
似乎没有保留对正在写入的文件的引用。您需要做的是发现什么
File
或路径(String
)被传递到FileOutputStream
并使用相同的File< /code> 或
String
创建新的FileInputStream
。You certainly can't read from an
OutputStream
. I think you mean you want to read from the file being written to by theFileOutputStream
. I don't think you can do that either. TheFileOutputStream
doesn't seem to keep a reference to the file being written to.What you need to do is discover what
File
or path (aString
) was passed into theFileOutputStream
and use that sameFile
orString
to create a newFileInputStream
.如果您希望能够在写入后读取内容(而不刷新到磁盘),请使用 ByteArrayOutputStream 和 ByteArrayInputStream。完成对 ByteArrayOutputStream 的写入后,您可以获取底层字节数据并使用 ByteArrayInputStream 将其读回。
如果你想要一个缓冲区(生产者/消费者类型问题),请查看java的nio包提供的缓冲区。
If you mean that you want to be able to read the contents after writing (without flushing to disk), use a ByteArrayOutputStream and a ByteArrayInputStream. Once you're done writing to the ByteArrayOutputStream, you can get the underlying byte data and use a ByteArrayInputStream to read it back.
If you want a buffer (producer/consumer type problem), look into the Buffers provided with java's nio package.
如果您可以使用@Thomas给出的示例,否则您可以这样做:
来自java2s.com的示例
编辑:
由于@Thomas删除了他的答案,我将仅添加用于处理此问题的参考Commons IO方法:
If you can use @Thomas example given, otherwise you can do:
example from java2s.com
EDIT:
As @Thomas deleted his answer, I will just add for reference Commons IO approach for handling this:
你想要的是一个 RandomAccessFile。它具有与 FileInputStream 和 FileOutputStream 相同的基本方法。我知道,你可能没有得到这个。
What you want is a RandomAccessFile. This has the same basic methods of both the FileInputStream and a FileOutputStream. I know, you probably aren't given that.