JAVA之IO技术-自定义的LineNumberReader类
时间:2014-05-03 16:50:06
收藏:0
阅读:341
package ioTest.io2; /* * 自定义一个带有读取行号方法的读取文件的装饰类 */ import java.io.FileReader; import java.io.IOException; import java.io.Reader; public class MyLineNumberReaderDemo { public static void main(String[] args) throws IOException { String line; //创建输入流-读取文件信息到流中区,所以对于流来讲是“入”了 FileReader in=new FileReader("BufferedWriterDemo.java"); MyLineNumberReader mlnr=new MyLineNumberReader(in); while((line=mlnr.MyReadLine())!=null) { System.out.println(mlnr.getLineNumber()+":"+line); } mlnr.close(); } } //定义一个自定义的类似于LineNumberReader的类 class MyLineNumberReader extends Reader{ private Reader r; int lineNumber; int ch=0; String line=null; //根据构造函数判断,显然此类也是一个构造类 MyLineNumberReader(Reader r) { this.r=r; } public String MyReadLine() throws IOException { lineNumber++; StringBuilder sBuilder=new StringBuilder(); while((ch=r.read())!=-1) { if(ch==‘\n‘) continue; if(ch==‘\r‘) return sBuilder.toString(); else sBuilder.append((char)ch); } if(sBuilder.length()>0) return sBuilder.toString(); return null; } public int getLineNumber() { return lineNumber; } public void setLineNumber(int lineNumber) { this.lineNumber = lineNumber; } @Override public int read(char[] cbuf, int off, int len) throws IOException { // TODO Auto-generated method stub return 0; } @Override public void close() throws IOException { // TODO Auto-generated method stub r.close(); } }
评论(0)