各位如果觉得好的话,请施舍一点辛苦分给我,谢谢
- package cn.itcast.ruxue;
- import java.io.BufferedReader;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.Reader;
- /*
- *
- * 6、 自定义字符输入流的包装类,通过这个包装类对底层字符输入流进行包装,让程序通过这个包装类读取某个文本文件(例如,一个java源文件)时,能够在读取的每行前面都加上有行号和冒号。
- *
- * */
- public class Test6 {
-
- public static void main(String[] args) throws IOException {
-
- FileReader f = new FileReader("C:\\Users\\lenovo\\Desktop\\Test5.java");
- MyReader mr = new MyReader(f);
- String line = null;
- while((line=mr.MyReadLineWithLineNumber())!=null){
- System.out.println(line);
- }
- mr.close();
- }
- }
- class MyReader extends Reader{
-
- //底层字符输入流
- private Reader reader;
- //自定义流中的缓冲区
- private char[] buffer = new char[1024];
- //记住缓冲区中剩下的字符数
- private int count = 0;
- //记住当前读到字符的缓冲区角标
- private int pos = 0;
- //记住行号
- private int lineNumber = 1;
-
- public MyReader(Reader reader){
- this.reader = reader;
- }
-
- //自定义的从缓存区读取单个字符的方法
- public int MyRead() throws IOException{
- if(count==0){
- count = reader.read(buffer);
- pos = 0;
- if(count<0){
- return -1;
- }
- }
- char ch = buffer[pos];
- count--;
- pos++;
- return ch;
- }
-
- //在缓存区读取一行的方法
- public String MyReadLineWithLineNumber() throws IOException{
- StringBuffer sb = new StringBuffer();
- int ch = 0;
-
- while((ch=MyRead())!=-1){
- if(ch=='\r'){
- continue;
- }
- if(ch=='\n'){
- return (lineNumber++) +" ::::: "+sb.toString();
- }
- sb.append((char)ch);
- }
- if(sb.length()>0){
- return (lineNumber++) +" ::::: "+sb.toString();
- }
- return null;
- }
-
- //关闭流的方法
- public void close() throws IOException{
- reader.close();
- }
-
- public int read(char[] cbuf, int off, int len) throws IOException {
- // TODO Auto-generated method stub
- return 0;
- }
- }
复制代码
|