LineNumberReader比BufferedReader多了个功能,就是可以返回当前行号。另外setLineNumber能改变行号,却不能改变读的位置。
测试代码:
package com.io;
import java.io.Closeable;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import junit.framework.TestCase;
public class TestLineNumberReader extends TestCase {
public void testLineNumberReader() {
LineNumberReader lineNumberReader = null;
FileReader fileReader = null;
try {
fileReader = new FileReader("c:/TestLineNumberReader.txt");
lineNumberReader = new LineNumberReader(fileReader);
String line = null;
while ((line = lineNumberReader.readLine()) != null) {
System.out.println(lineNumberReader.getLineNumber() + ": " + line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
close(lineNumberReader);
close(fileReader);
}
}
private void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
closeable = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}