BufferedReader 到 BufferedWriter
如何从 BufferedReader
获取 BufferedWriter
?
我希望能够做这样的事情:
BufferedReader read = new BufferedReader(new InputStreamReader(...));
BufferedWriter write = new BufferedWriter(read);
How can I obtain a BufferedWriter
from a BufferedReader
?
I'd like to be able to do something like this:
BufferedReader read = new BufferedReader(new InputStreamReader(...));
BufferedWriter write = new BufferedWriter(read);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用 Apache commons io 中的以下内容:
站点此处
You can use the following from Apache commons io:
site here
JAVA 9 更新
从 Java 9 开始,Reader 提供了一个名为 transferTo 的方法,其签名如下:
正如文档所述,transferTo 将:
从该 reader 读取所有字符,并按顺序将字符写入给定 writer他们被阅读了。返回时,该读取器将位于流的末尾。此方法不会关闭读取器或写入器。
此方法可能会无限期地阻止读取器读取或写入写入器。读取器和/或写入器异步关闭或线程在传输期间中断的情况的行为是高度特定于读取器和写入器的,因此未指定。
如果从读取器读取或写入写入器时发生 I/O 错误,则可能会在读取或写入某些字符后发生此错误。因此,读取器可能不在流的末尾,并且一个或两个流可能处于不一致的状态。强烈建议如果发生 I/O 错误,立即关闭两个流。
因此,为了将 Java Reader 的内容写入 Writer,您可以编写:
JAVA 9 Updates
Since Java 9, Reader provides a method called transferTo with the following signature:
As the documentation states, transferTo will:
Reads all characters from this reader and writes the characters to the given writer in the order that they are read. On return, this reader will be at end of the stream. This method does not close either reader or writer.
This method may block indefinitely reading from the reader, or writing to the writer. The behavior for the case where the reader and/or writer is asynchronously closed , or the thread interrupted during the transfer, is highly reader and writer specific, and therefore not specified.
If an I/O error occurs reading from the reader or writing to the writer, then it may do so after some characters have been read or written. Consequently the reader may not be at end of the stream and one, or both, streams may be in an inconsistent state. It is strongly recommended that both streams be promptly closed if an I/O error occurs.
So in order to write contents of a Java Reader to a Writer, you can write:
如果您想知道发生了什么:
来自阅读器的所有输入都被复制到输入流
也类似:
有关输入和输出的更多信息 真正的大索引
If you want to know what happens:
All input from the reader is copied to the inputstream
Something similar too:
More on input and output on The Really big Index
BufferedWriter 构造函数没有为接受读取器重载,对吧?布赫布说的是正确的。
BufferedWriter constructor is not overloaded for accept readers right? what Buhb said was correct.
您可以使用管道读取/写入器(链接 )。这正是它们的设计目的。不确定您是否可以将它们重新连接到您通过的现有缓冲读取器上。您必须特意围绕它自己构建 buf 读取器。
You could use Piped Read/Writers (link). This is exactly what they're designed for. Not sure you could retcon them onto an existing buffered reader you got passed tho'. You'd have to construct the buf reader yourself around it deliberately.