a- package demo.io;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.Reader;
- public class IODemo5_MyBufferedReader {
- /**
- * 模拟一个缓冲区 1 有数组 2 数组下标 3 缓冲区内容长度
- * @throws IOException
- */
- public static void main(String[] args) throws IOException {
- File srcFile = new File("c:\\Java review", "Test7.java");
- MybufferedReader fr = null;
- try {
- fr = new MybufferedReader(new FileReader(srcFile));
- String line = null;
- while((line = fr.readLine())!=null)
- System.out.println(line);
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }finally{
- if(fr != null)
- try {
- fr.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- class MybufferedReader {
- private Reader r;
- private int count = 0;
- private int pos = 0;
- private char[] cbuf = new char[1024];
- public MybufferedReader(Reader r) {
- this.r = r;
- }
- // 读单字符
- public int read() throws IOException {
- int ch = 0;
- if (count == 0) {
- count = r.read(cbuf);
- pos = 0;
- } else if (count < 0) {
- return -1;
- } else {
- ch = cbuf[pos++];
- count--;
- }
- return ch;
- }
- // 行读取
- public String readLine() throws IOException {
- StringBuilder sb = new StringBuilder("");
- int ch;
- while ((ch = read()) != -1) {//调用自身的函数提高代码复用性
- if ((char) ch == '\r')
- continue;
- if ((char) ch == '\n')
- return sb.toString();
- sb.append((char) ch);
- }
- if (sb.length() > 0)
- return sb.toString();
- return null;
- }
- public void close() throws IOException{
- r.close();
- }
- }
复制代码
|
|