自建模仿类一:
package cn.itcast_09;
import java.io.IOException;
import java.io.Reader;
public class MyLineNumberReader {
private Reader r;
private int lineNumber = 0;
public MyLineNumberReader(Reader r) {
this.r = r;
}
public int getLineNumber() {
// lineNumber++;
return lineNumber;
}
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
public String readLine() 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 void close() throws IOException {
this.r.close();
}
}
自建模仿类二:【需要结合上一篇《用Reader模拟BufferedReader的特有功能 readline()》完成】
package cn.itcast_09;
import java.io.IOException;
import java.io.Reader;
import cn.itcast_08.MyBufferedReader;
public class MyLineNumberReader2 extends MyBufferedReader {
private Reader r;
private int lineNumber = 0;
public MyLineNumberReader2(Reader r) {
super(r);
}
public int getLineNumber() {
return lineNumber;
}
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
@Override
public String readLine() throws IOException {
lineNumber++;
return super.readLine();
}
}
Demo测试:
package cn.itcast_09;
import java.io.FileReader;
import java.io.IOException;
public class MyLineNumberReaderTest {
public static void main(String[] args) throws IOException {
// MyLineNumberReader mlnr = new MyLineNumberReader(new FileReader(
// "my.txt"));
MyLineNumberReader2 mlnr = new MyLineNumberReader2(new FileReader(
"my.txt"));
// mlnr.setLineNumber(10);
// System.out.println(mlnr.getLineNumber());
// System.out.println(mlnr.getLineNumber());
// System.out.println(mlnr.getLineNumber());
String line = null;
while ((line = mlnr.readLine()) != null) {
System.out.println(mlnr.getLineNumber() + ":" + line);
}
mlnr.close();
}
}