差点就理解错了,这里不能直接调用LineNumberReader!
自定义字符输入流的包装类,通过这个包装类对底层字符输入流进行包装,让程序通过这个包装类读取某个文本文件(例如,一个java源文件)时,能够在读取的每行前面都加上有行号和冒号。
package com.jwd.black.exam;
import java.io.*;
public class Exam8 {
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("f:\\exam8.java");
MyLineNumberReader lnr = new MyLineNumberReader(fr);
String line = null;
while ((line = lnr.myReadLine()) != null) {
System.out.println(lnr.getLineNumber() + ":" + line);
}
lnr.myClose();
}
}
class MyLineNumberReader {
private Reader r;
private int lineNumber;
MyLineNumberReader(Reader r) {
this.r = r;
}
public String myReadLine() throws IOException {
lineNumber++;
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);
}
if (sb.length() != 0)
return sb.toString();
return null;
}
public int getLineNumber() {
return lineNumber;
}
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
public void myClose() throws IOException {
r.close();
}
}
|
|