美文网首页
readline方法

readline方法

作者: 实在想不出昵称丶 | 来源:发表于2017-01-14 23:06 被阅读0次

    January201705



    /**
    根据 BufferedReader类中的特有方法  ReadLine()
    自己定义一个方法  模拟 ReadLine()方法
    定义一个容器,在读取至  换行符时  进行截断。
    */
    import java.io.*;
    public class demo{
      public static void main(String[] args)throws IOException{
        myBufferedReader mbf=new myBufferedReader(new FileReader("Test.java"));
        String s=null;
        while((s=mbf.myReadLine())!=null){
          System.out.println(s);
        }
      /*  while((s=mbf.myReadLineTwo())!=null){
          System.out.println(s);
        }*/
      //  s=mbf.myReadLineTwo();
      //  System.out.println(s);
      }
    }
    class myBufferedReader{
      private FileReader r;
      public myBufferedReader(FileReader r){
        this.r=r;
      }
    /*  public String myReadLineTwo()throws IOException{
        //定义一个字符数组,作为缓冲
        char[] buf =new char[1024];
        int ch=0;
        while((ch=r.read(buf))!=-1){
          if(ch=='\r')
              continue;
          if(ch=='\n')
             return String.valueOf(buf);
    
        }
        return null;
      }*/
      public String myReadLine()throws IOException {
       //定义一个临时容器。与bufferedReader封装的是字符数组
        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()throws IOException{
        r.close();
      }
    
    }
    
    
    

    相关文章

      网友评论

          本文标题:readline方法

          本文链接:https://www.haomeiwen.com/subject/jjkybttx.html