• java 自定义BufferedReader_readLine


    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.Reader;
    
    public class BufferedReaderDemo {
    
    	public static void main(String[] args) {
    		MyBufferedReader mbr = null;
    		try {
    			mbr = new MyBufferedReader(new FileReader("src/D.java"));
    			for (String line; (line = mbr.myReadLine()) != null;)
    				System.out.println(line);
    		} catch (FileNotFoundException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			try {
    				if (mbr != null) {
    					mbr.myClose();
    					mbr = null;
    				}
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    	}
    
    }
    
    /*
     * 自定义字符输入流缓冲区
     */
    class MyBufferedReader {
    	//缓冲区中的字符流
    	private Reader r = null;
    
    	public MyBufferedReader(Reader r) {
    		this.r = r;
    	}
    
    	public String myReadLine() throws IOException {
    		//该方法缓冲数据的容器
    		StringBuilder sb = new StringBuilder();
    		
    		/*
    		 * 未读到回车换行就把读到的数据添加到
    		 * 容器中,读到回车换行就把数据返回
    		 */
    		for (int ch; (ch = r.read()) != -1;) {
    			if (ch == '
    ')
    				continue;
    			if (ch == '
    ')
    				return sb.toString();
    			else {
    				sb.append((char) ch);
    			}
    		}
    		
    		/*
    		 * 为了避免文件结尾无回车换行
    		 * 只要容器中有数据最后就返回
    		 */
    		if (sb.length() != 0) {
    			return sb.toString();
    		}
    		return null;
    	}
    
    	public void myClose() throws IOException {
    		r.close();
    	}
    
    }


  • 相关阅读:
    抱歉
    The area
    sort
    Problem D
    Problem B
    错排
    第8集 仪表开关电源照明原理图
    第7集 驱动与电气原理图绘制
    第6集 初步使用EPLAN部件库部件功能
    第5集 软件中建立项目结构
  • 原文地址:https://www.cnblogs.com/riasky/p/3478837.html
Copyright © 2020-2023  润新知