[英]How can I mix Java OutputStream with OutputStreamWriter?
I am currently writing a lot of text to a file using a BufferedWriter. 我目前正在使用BufferedWriter将大量文本写入文件。 I pass the BufferedWriter object around to various functions in my code.
我将BufferedWriter对象传递给代码中的各种函数。 I now need to use a stream object in my functions in order to use the Base64OutputStream class in one place.
现在,我需要在函数中使用流对象,以便在一处使用Base64OutputStream类。 I'm unsure how to change all of my code without needing to convert strings to bytes for every .write() call and also avoid calling helper functions like IOUtils.write() since that sounds like it would impact performance.
我不确定如何更改所有代码,而无需为每个.write()调用将字符串转换为字节,并且还避免调用诸如IOUtils.write()的帮助器函数,因为这听起来会影响性能。
Shall I just give in and call the IOUtils.write() function for the string writes? 我是否应该让步并调用IOUtils.write()函数进行字符串写入? The code is certainly ugly compared to a clean call to a stream or writer write() function.
与对流或写入器write()函数的干净调用相比,该代码肯定很难看。
Could I create both a stream object and a writer object and pass both around, switching between them as needed (which sounds like it would just crash or cause corruption)? 我可以同时创建一个流对象和一个写程序对象,并在两者之间传递,并根据需要在它们之间切换(这听起来会崩溃或导致损坏)吗?
Java is a second language for me so I don't know off the top of my head all of the possible classes and functions available to me. Java对我来说是第二语言,所以我不了解我可能拥有的所有可能的类和函数。 I would like the code to be as readable and maintainable as possible.
我希望代码尽可能的可读性和可维护性。
An
OutputStreamWriter
is a bridge from character streams to byte streamsOutputStreamWriter
是从字符流到字节流的桥梁
So you can create an OutputStream
, wrap it in an OutputStreamWriter
, and writing to the OutputStreamWriter
will encode characters to bytes and call the corresponding OutputStream.write
. 因此,您可以创建一个
OutputStream
,将其包装在OutputStreamWriter
,然后写入OutputStreamWriter
会将字符编码为字节,然后调用相应的OutputStream.write
。
In this specific case do note that documentation says 在这种特定情况下,请注意文档说明
It is mandatory to close the [
Base64OutputStream
] after the last byte has been written to it, otherwise the final padding will be omitted and the resulting data will be incomplete/inconsistent必须在写入最后一个字节后关闭[
Base64OutputStream
],否则最后的填充将被省略,并且结果数据将不完整/不一致
which closes the underlying stream in turn. 依次关闭基础流。 So if writing to
Base64OutputStream
isn't your last operation, you may need to close and reopen the original stream, invalidating the Writer
. 因此,如果不是最后一次写入
Base64OutputStream
则可能需要关闭并重新打开原始流,从而使Writer
无效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.