本帖最后由 陈延真 于 2013-6-2 20:08 编辑
//需求:模拟LineNumberReader类
/*
模拟除了有readLine()方法和close()方法外。还应该有获取和设置行号的功能。
*/
import java.io.IOException;
import java.io.Reader;
public class MyLineNumberReader {
private Reader r;
private int lineNumber;
public MyLineNumberReader(Reader r) {
this.r = r;
}
public int getLineNumber() {
return lineNumber;
}
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
// 模拟readLine()方法
public String readLine() throws IOException {
lineNumber++;
// 定义一个容器
StringBuilder sb = new StringBuilder(); // sb
int ch = 0;
while ((ch = r.read()) != -1) {
// ch是不是就是读取到的字符
if (ch == '\r') {
continue;
}
if (ch == '\n') {
return sb.toString(); // hello
} else {
sb.append((char) ch); // hello java
}
}
return null;
}
// 释放资源
public void close() throws IOException {
r.close();
}
}
//下面是测试类
import java.io.FileReader;
import java.io.IOException;
public class MyLineNumberReaderTest {
public static void main(String[] args) throws IOException {
MyLineNumberReader mlnr = new MyLineNumberReader2(new FileReader(
"a.txt"));
mlnr.setLineNumber(10);
String line = null;
while ((line = mlnr.readLine()) != null) {
System.out.println(mlnr.getLineNumber() + ":" + line);
}
mlnr.close();
}
}
|