Examples are as follows:
package day0208; import java.io.FileReader;import java.io.IOException; /* * Custom read buffer to implement the BufferedReader function* Analysis: * Buffer is to encapsulate an array and provide more methods to access the array* In fact, these methods ultimately operate the angle mark of the array* Principle of buffering: * In fact, it is to obtain a batch of data from the source and load it into the buffer, and then extract data from the buffer* After this collection, continue to extract a batch of data from the source to the buffer* When the data in the source is extracted, use -1 as the end mark. */public class MyBufferReader { private FileReader r; MyBufferReader(FileReader r){ this.r=r; } //Define an array as a buffer private char[] buf=new char[1024]; //Define a pointer to operate the elements of this array. When the last element is operated, the pointer should reset to zero private int pos=0; //Define a counter to record the number of data in the buffer. When the data is reduced to 0, continue to obtain data from the source and into the buffer. private int count =0; public int myRead() throws IOException{//Custom read method if(count==0){//If there is no data in the buffer, get a batch of data from the source to the buffer count=r.read(buf); pos=0; } if(count<0){ return -1; } char ch=buf[pos++];//Get one character from the buffer at a time count--; return ch; } public String myReadLine() throws IOException{//Custom readLine violates the law StringBuilder sb=new StringBuilder(); int ch=0; while((ch=myRead())!=-1){//As long as there is data, read if(ch=='/n')//java line breaks, stop reading, and return the read data output to return sb.toString(); if(ch=='/r') continue;//The newline under window, do not read or line break, continue to read the following characters sb.append((char)ch);//Under normal circumstances, keep reading} if(sb.length()!=0)//If there are characters in the document, return sb.toString(); return null;//If it is an empty document, return empty} public void myClose() throws IOException{ r.close();//Close flow resources}}This will be OK, and you can perform testing
package day0208; import java.io.FileReader;import java.io.IOException; public class MyDemo { public static void main(String[] args) throws IOException { FileReader fw=new FileReader("C://demo2.txt"); MyBufferReader br=new MyBufferReader(fw); String line1=null; while((line1=br.myReadLine())!=null){ System.out.println(line1); }// int num=0;// while((num=br.myRead())!=-1){// System.out.print((char)num);// } br.myClose(); }}Both detection methods are OK.
The above article is based on the read and readLine method in the custom BufferedReader. This 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.