- package nineteen;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.IOException;
- public class MyLineNumberReaderDemo {
- public static void main(String[] args) {
- FileReader fr ;
- try {
- fr = new FileReader("D:\\test.java");
- MyLineNumberReader mybr=new MyLineNumberReader(fr);
- String len=null;
- try {
- while((len=mybr.MyLinenumberReadLine())!=null){
- System.out.println(len);
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- try {
- mybr.myclose();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- } catch (FileNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- class MyLineNumberReader{
- private FileReader r;
- public MyLineNumberReader(FileReader r){
- this.r=r;
- }
- public String MyLinenumberReadLine() throws IOException{
- StringBuilder sb=new StringBuilder();
- int ch=0;
- int num=1; //定义一个计数器
- while((ch=r.read())!=-1){
- if(ch=='\r'){
- continue;
- }
- if(ch=='\n'){
- num = num++;
- return num+sb.toString();
- }
- else{
- sb.append((char)ch);
- }
- }
- return null;
- }
- public void myclose() throws IOException{
- r.close();
- }
- }
复制代码 这样就可以了 你的是因为 num虽然每次都++;但是并没有赋予原来的值
所以每次循环 num的值都没有变,都是1,然后再次循环,所以每次行号都是1 |