Reader 简介

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class ReaderDemo {
   /*
    * Reader:字符输入流
    * FileReader:文件字符输入流,以字符为单位进行读取内容
    * --->构造方法
    * 1.new FileReader(File file)
    *  参数File对象代表文件源
    * 2.new FileReader(String pathName)
    *  参数String路径表示文件为文件源
    */
   public static void main(String[] args) {
      Reader fr = null;
      try {
         fr=    new FileReader("D:/demo/test/b.txt");
         /*
          * int | read():一次读取一个字符,
          * 返回该字符的Unicode编码
          */
      /* int i = fr.read();
         System.out.println((char)i);
         */
         /*
          * int | read(char[] cbuf):
          * 把每次读取到的字符存入char数组中,
          * 返回每次读取到的字符的个数。
          * 如果不存在内容了返回-1
          */
      /* String str = "";
         int len = 0;
         char[] cbuf = new char[3];
         while((len = fr.read(cbuf)) != -1){
            String s = String.valueOf(cbuf, 0, len);
            str += s;
         }
         System.out.println(str);
         */
         /*
          * int | read(char[] cbuf,int off,int len):
          * 把每次读取到的字符存到char数组从下标为off开始
          * 存入,每次最多存入len个字符。
          * 返回值每次读取到的字符的个数
          */
         char[] cbuf = new char[3];
         int len = 0;
         String str = "";
         while((len = fr.read(cbuf, 1, 2)) != -1){
            String s = new String(cbuf,1,len);
            str += s;
         }
         System.out.println(str);
      } catch (IOException e) {
         e.printStackTrace();
      }finally{
         if(fr != null){
            try {
               fr.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }
   }
}

猜你喜欢

转载自blog.csdn.net/Peter_S/article/details/86614455
今日推荐