链结串流可以单独使用或与连结串流并用。这是ㄚ琪在看是深入浅出 Java 程式设计 第二版第十四章的序列话语档案输出入时碰到的问题,一开始ㄚ琪有点傻眼,链跟连一般不是都是一样的意义吗?怎会出现这样的问题,当然如果课本会这样出题的话,表示这两个字确实是有分别的,可是ㄚ琪不清楚这里的差异,翻开英文版的来看,‘Chain streams can be used on their own or with connection streams.’Chain streams译成炼结串流,connection streams译成连结串流,单独看这个英文还是不懂,还真让人苦恼。
而且Google的时候大部分都是跟这本书有关的资料才有Chain stream,所以让ㄚ琪继续看看,‘The I/O API uses the modular ‘chaining’ concept so that you can hook together connection streams and chain
streams (also called ‘filter’ streams) In a wide range of combi nations to get Just about anyth Ing you couId want .’在中文p.459没有蠢问题这里,第一个问题,‘我查API的时候发现java.io这个package中有五百万种class,你到底是怎么知道要用哪一种?’
答案第一段,‘I/O的API使用一种模组化的链接概念来让你可以把连接串流与链接串流以各种可能应用到的排列组合连接起来。’注意,英文有这样一句chain streams (also called ‘filter’ streams),这是中文没有翻出的,filter stream Google到这样一段简报,Java的“过滤串流”(Filter Stream)是在串流间加上过滤器,以便将上方串流的资料在处理后,才送到下方的串流,如下图所示:
把矛头对准在过滤串流看来是对的,再追溯到中文课本的p433,有解释资料在串流中移动,英文是这样‘
The java I/O API has amnection streams, that represent connections to destinations and
sources such as files or network sockets, and chain streams that work only if chained to
other streams.
Often, it takes at least two streams hooked together to do something useful-one to
represent the connection and anotherto call methods on. \\Thy two? Because connection
streams are usually too low-level. FileOutputStream (a connection stream), for example,
has methods for writing byles. But we don’t want to write byusl We want to write objects, so
we need a higher-level chain stream.
OK, then why not have just a single stream that does exactly what you want? One that lets
you write objects but underneath converts them to bytes? Think good 00. Each class
does onething well. File OurpurStreams write bytes to a file. ObjectOurputStreams turn
objects into data that can be written to a stream. So we make a FileOutputStream that lets
us write to a file, and we hook an ObjectOutputStrearn (a chain stream) on the end of it.
When we call writeObject() on the ObjectOutputStream. the object gets pumped into the
stream and then moves to the FileOutputStream where it ultimately gets written as bytes
to a file.
The ability to mix and match different combinations of connection and chain streams
gives you tremendous flexibilityl Ifyou were forced to use only a singlestream class, you’d
be at the mercy of the APIdesigners. hoping they’d thought of everythitlgyou might ever
want to do. But with chaining, you can patch together your own custom chains.
’
看了图之后,更懂了,chain stream应该叫做filter stream真的比较容易懂,我的空气又再度新鲜起来了。