将流引用保持“进一步向下”过滤链,再次使用那些较低级别的流,甚至将一种类型的流交换为另一种流是不好的风格? 例如:
OutputStream os = new FileOutputStream("file"); PrintWriter pw = new PrintWriter(os); pw.print("print writer stream"); pw.flush(); pw = null; DataOutputStream dos = new DataOutputStream(os); dos.writeBytes("dos writer stream"); dos.flush(); dos = null; os.close();如果是这样,如果我需要使用两个流的功能,有什么选择,例如,如果我想将一行文本写入流,然后是二进制数据,反之亦然?
Is it bad style to keep the references to streams "further down" a filter chain, and use those lower level streams again, or even to swap one type of stream for another? For example:
OutputStream os = new FileOutputStream("file"); PrintWriter pw = new PrintWriter(os); pw.print("print writer stream"); pw.flush(); pw = null; DataOutputStream dos = new DataOutputStream(os); dos.writeBytes("dos writer stream"); dos.flush(); dos = null; os.close();If so, what are the alternatives if I need to use the functionality of both streams, e.g. if I want to write a few lines of text to a stream, followed by binary data, or vice versa?
最满意答案
这可以在某些情况下完成,但它容易出错。 您需要注意缓冲区和ObjectOutputStream的流标题之类的东西。
如果我想在流中写几行文本,然后是二进制数据,反之亦然?
为此,您需要知道的是,您可以将文本转换为二进制数据并返回,但始终需要指定编码。 但是,它也容易出错,因为人们倾向于使用使用平台默认编码的API方法,当然你基本上是为自定义二进制文件格式实现解析器 - 很多东西都可能出错。
总而言之,如果您正在创建文件格式,特别是在混合文本和二进制数据时,最好使用现有的框架,如Google协议缓冲区
This can be done in some cases, but it's error-prone. You need to be careful about buffers and stuff like the stream headers of ObjectOutputStream.
if I want to write a few lines of text to a stream, followed by binary data, or vice versa?
For this, all you need to know is that you can convert text to binary data and back but always need to specify an encoding. However, it is also error-prone because people tend to use the API methods that use the platform default encoding, and of course you're basically implementing a parser for a custom binary file format - lots of things can go wrong there.
All in all, if you're creating a file format, especially when mixing text and binary data, it's best to use an existing framework like Google protocol buffers
更多推荐
发布评论