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 java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.IOException;public class ReadFile3 { public static void main(String[] args) { try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream("F:/data.txt"))){ int b; while((b = bin.read()) != -1){ System.out.print((char)b); } } catch (IOException e) { e.printStackTrace(); } }}
Stream filter streams (link filters together)