在Java中流链接(Stream chaining in Java)

系统教程 行业动态 更新时间:2024-06-14 16:57:18
在Java中流链接(Stream chaining in Java)

将流引用保持“进一步向下”过滤链,再次使用那些较低级别的流,甚至将一种类型的流交换为另一种流是不好的风格? 例如:

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

更多推荐

本文发布于:2023-04-12 20:42:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/4b644382129410e3985c27f5c04339ab.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中流   链接   Java   Stream   chaining

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!