/*使用LineNumberReader方法来实现读取文件
*/
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Reader;
public class LineNumberReaderDemo {
public static void main(String[] args) {
/*//通过使用LineNumberReader方法来实现读取文件
* FileReader fr=null;
LineNumberReader lnr=null;
try {
fr=new FileReader("D:\\Android\\Android\\eclipse\\workspace\\bixiangdongjava\\src\\bxdjava19day\\PersonDemo.java");
lnr=new LineNumberReader(fr);
String line=null;
lnr.setLineNumber(100);
while ((line=lnr.readLine())!=null) {
System.out.println(lnr.getLineNumber()+":"+line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
lnr.close();
} catch (IOException e) {
e.printStackTrace();
}
}*/
//演示LineNumberReader行号是特点
FileReader fr=null;
MyLineNumberReaderDemo mlnrd=null;
try {
fr=new FileReader("D:\\Android\\Android\\eclipse\\workspace\\"
+ "bixiangdongjava\\src\\bxdjava19day\\PersonDemo.java");
mlnrd=new MyLineNumberReaderDemo(fr);
String line=null;
//mlnrd.setLineNumber(100);//指定开始的行数,默认的是从零开始
while ((line=mlnrd.myReaderLine())!=null) {
System.out.println(mlnrd.getLineNumber()+":"+line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
mlnrd.myClose();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class MyLineNumberReaderDemo{
private Reader r;
private int lineNumber;
public String myReaderLine() throws IOException {
lineNumber++;//读一行linenumber自增一次
StringBuilder sb=new StringBuilder();
int ch=0;
while ((ch=r.read())!=-1) {
if (ch=='\r') {
continue;
}else 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 MyLineNumberReaderDemo(Reader r) {
super();
this.r = r;
}
public void myClose ()throws IOException {
r.close();
}
}