Stream filter streams (link filters together)

Source: Internet
Author: User

The filter is constructed through it.Function and stream connection.For example, the following code field will buffer the input of the data.txt file:

InputStream in = new FileInputStream("F:/data.txt");BufferedInputStream bin = new BufferedInputStream(in);

Reading a file from data.txt may use both the in and bin read () methods. However, if the mixed call is connected to different streams of the same source, this may violate some implicit conventions of the filter stream. In most cases,Only the last filter in the chain should be used for actual read/write.To avoid this bug when writing code, you can intentionally override the reference of the underlying input stream. For example:

InputStream in = new FileInputStream("F:/data.txt");in = new BufferedInputStream(in);

After the two lines of code are executed, there is no way to access the underlying file input stream, so you will not accidentally read the stream and destroy the buffer zone. Of course, you can also directly build another stream in one stream, for example:

DataOutputStream dout = new DataOutputStream(    new BufferedOutputStream(new FileOutputStream("F:/data.txt")));

Sometimes you may need to use the linkMultiple Filters. However,Except for the last filter in the chain, you should not read data from other filters or write anything to them..

Let's take a complete example:

package test;import;import;import;public class ReadFile3 {    public static void main(String[] args) {        try (BufferedInputStream bin =             new BufferedInputStream(new FileInputStream("F:/data.txt"))){            int b;            while((b = != -1){                System.out.print((char)b);            }        } catch (IOException e) {            e.printStackTrace();        }    }}

Stream filter streams (link filters together)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.