The purpose of establishing a buffer is to increase transmission performance and make us transmit data faster.
The buffer is actually very simple. It encapsulates an array internally and uses an array to store data to provide some methods to access the array.
The operation of these methods is to pointers to the array (angle markers).
The principle of buffer: Get a batch of data from the source to the buffer, then take it out one by one from the buffer and use -1 as the end mark.
In the BufferedReader, we have read() and readLine() methods to read data.
read() has parameters char[],cbuf,int off,int len. Its return value is -1
The readLine() method is to take the inside of it line by line like a string container StringBuffder whose return value is null;
First, define a class to define two methods for reading data in the class MyReader() and MyReadLine();
public class MyBufferedReader { private FileReader fr; private char[] buff = new char[1024]; private int zz = 0; private int count = 0; MyBufferedReader(FileReader fr){ this.fr = fr; } public int MyRead() throws IOException{ if(count==0){ count = fr.read(buff); zz = 0; } if(count<0) return -1; char ch = buff[zz++]; count--; return ch; } public String MyReadLine() throws IOException{ StringBuilder stb = new StringBuilder(); int ch = 0; while((ch=MyRead())!=-1){ if(ch=='/r') continue; if(ch=='/n') return stb.toString(); stb.append((char)ch); } if(stb.length()!=0) return stb.toString(); return null; } public void MyClose() throws IOException{ fr.close(); }}In it, I define a pointer zz and a buffer counter count to record the changes in the read data in the buffer
When count==0, read data into the buffer zz 0. Read from the first number
When the data is less than 0, it returns -1 after reading.
Create a string container StringBuilder in MyReadLine() to store data. When stb==/n, a line is read and its return value is null;
The above example of custom BufferedReader is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.