美文网首页
2021-08-29 IO流(MyBufferedReader)

2021-08-29 IO流(MyBufferedReader)

作者: Denholm | 来源:发表于2021-09-18 15:30 被阅读0次

    自定义BufferedReader,模拟readLine方法

    import java.io.FileReader;
    import java.io.IOException;
    
    class MyBufferedReader {
    
        private FileReader fileReader;
    
        public MyBufferedReader(FileReader fileReader) {
            this.fileReader = fileReader;
        }
    
        public String myReadLine() throws IOException {
            StringBuilder builder = new StringBuilder();
            int ch;
            while ((ch = fileReader.read()) != -1) {
                if (ch == '\r') {
                    continue;
                }
                if (ch == '\n') {
                    return builder.toString();
                } else {
                    builder.append((char) ch);
                }
            }
    
            if (builder.length() != 0) {
                return builder.toString();
            }
    
            return null;
        }
    
        public void myClose() throws IOException {
            fileReader.close();
        }
    
    }
    
    public class MyBufferedReaderDemo {
    
        public static void main(String[] args) throws Exception {
            FileReader fileReader = new FileReader("E:\\demo.txt");
            MyBufferedReader myBufferedReader = new MyBufferedReader(fileReader);
            String line;
            if ((line = myBufferedReader.myReadLine()) != null) {
                System.out.println(line);
            }
            myBufferedReader.myClose();
        }
    
    }
    

    相关文章

      网友评论

          本文标题:2021-08-29 IO流(MyBufferedReader)

          本文链接:https://www.haomeiwen.com/subject/dlswiltx.html