自制MyLineNumberReader
import java.io.*; class MyBufferedReader extends Reader { private Reader r;//全局使用 MyBufferedReader(Reader r) { this.r = r; } public String myReadLine()throws IOException//一次读一行 { //StringBuilder StringBuilder sb = new StringBuilder(); int ch = 0; while ((ch=r.read())!=-1){ if(ch=='\r') continue; if(ch=='\n') return sb.toString(); else sb.append((char)ch); } return null; } public int read(char[] cbuf, int off, int len) //抽象类必须被复写 { return read(cbuf,off, len); } public void close()throws IOException { r.close(); } public void myClose()throws IOException { r.close(); } } class MyBufferedReaderDemo{ public static void main(String[] args) throws IOException { FileReader fr = new FileReader("buf.txt"); MyBufferedReader mybuf = new MyBufferedReader(fr); String line = null; while((line=mybuf.myReadLine())!=null){ System.out.println(line); } mybuf.myClose(); } }
使用已经写好的类
import java.io.*; /*class MyLineNumberReader { private Reader r; MyLineNumberReader(Reader r) { this.r=r; } private int num=0; //private BufferedReader buf; //buf = new BufferedReader(r); public int myGetLineNumber(){ return num; } public void mySetNumber(int num) { this.num=num; } public String myReadLine()throws IOException { num++; StringBuilder sb = new StringBuilder(); int ch = 0; while ((ch=r.read())!=-1){ if(ch=='\r') continue; if(ch=='\n') return sb.toString(); else sb.append((char)ch); } return null; } public int read(char[] cbuf, int off, int len) { return read(cbuf,off, len); } public void close()throws IOException { r.close(); } }*/ class MyLineNumberReader extends MyBufferedReader { private int num=0; MyLineNumberReader(Reader r){ super(r); } public String myReadLine()throws IOException { num++; return super.myReadLine(); } public int myGetLineNumber(){ return num; } public void mySetNumber(int num) { this.num=num; } } class MyLineNumberReaderDemo { public static void main(String[] args)throws IOException { FileReader fr = new FileReader("MyBufferedReaderDemo.java"); MyLineNumberReader mlnr= new MyLineNumberReader(fr); String str = null; mlnr.mySetNumber(100); while((str=mlnr.myReadLine())!=null) { System.out.println(mlnr.myGetLineNumber()+":"+str); } mlnr.close(); } }