默认情况下,行编号从 0 开始。该行号随数据读取在每个行结束符处递增,并且可以通过调用 setLineNumber(int)
更改行号。但要注意的是,setLineNumber(int)
不会实际更改流中的当前位置;它只更改将由 getLineNumber() 返回的值。可认为行在遇到以下符号之一时结束:换行符(‘\n‘)、回车符(‘\r‘)、回车后紧跟换行符。
FileReader fr = new FileReader(“demo.txt”);
LineNumberReader lnr = new LineNumberReader(fr);
String line = null;
lnr.setLineNumber(100);//从100开始计数,默认从1开始
while((line = lnr.readLine()) != null){
sysout(lnr.getLineNumber() + “:”+ line);
}
lnr.close();
-----------------------------------
模拟一个带行号的缓冲区对象
class MyLineNumberReader{
private Reader r;
private int lineNumber;
MyLineNumberReader(Reader r){
this.r = r;
}
public String myReadLine(){
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 myClose(){
r.close();
}
public void setLineNumber(int lineNumber){
this.lineNumber = lineNumber;
}
public int getLineNumber(){
return lineNumber;
}
main(){
FileReader fr = new FileReader(“copyTextByBuf.java”);
MyLineNumberReader mylnr = new MyLineNumberReader(fr);
String line = null;
while((line = mylnr.myReadLine()) != null){
sysout(line);
}
mylnr.myClose();
}
}
------------------------------
优化
class MyLineNumberReader extends MyBufferedReader{
private int lineNumber;
MyLineNumberReader(Reader r){
super(r);
}
public String myReadLine(){
lineNumber++;
return super.myReadLin();
}
public void setLineNumber(int lineNumber){
this.lineNumber = lineNumber;
}
public int getLineNumber(){
return lineNumber;
}
main(){
FileReader fr = new FileReader(“copyTextByBuf.java”);
MyLineNumberReader mylnr = new MyLineNumberReader(fr);
String line = null;
while((line = mylnr.myReadLine()) != null){
sysout(line);
}
mylnr.myClose();
}
}
LineNumberReader类