IO流(4)—字符流

1.IO体系:

  • 抽象基类 ——节点流(文件流)
  • InputStream —— FileInputStream
  • OutputStream ——FileOutputSteam
  • Reader ——FileReader
  • Writer ——FileWriter

2.分类:

  • 按操作数据单位不同:字节流(8bit)主要处理除了文本文件以外的问文件、字符流(16bit)主要处理文本文件
  • 按数据流的流向不同:输入流、输出流
  • 按流的角色不同:节点流(直接作用于文件的:FileInputStream、FileOutputSteam、FileReader、FileWriter)、
  • 处理流(除了以上四个之外都是)

    这里介绍字符流:

    • FileReader和FileWriter的使用
    • 主要用于处理文本文件,非文本文件使用字节流

3代码实例:

public class FileReaderWriter {

    //执行以下方法,计算使用FileReader和FileWriter传输文件使用的时间
        @Test
        public void testCopyFile(){
            long start = System.currentTimeMillis();
            String src = "file/hello.txt";
            String dest = "file/hello4.txt";
            testFileWriter(src,dest);
            long end = System.currentTimeMillis();
            System.out.println("花费时间:"+(end - start));//花费时间为1毫秒
        }
    //读取一个文本文件,然后写入到另一个文本文件中
    //@Test
    public void testFileWriter(String str1,String str2){
        //1.定义两个File类对象
        File src = new File(str1);
        File dest = new File(str2);
        //2.定义字符流
        FileReader fr = null;
        FileWriter fw = null;
        try {
            fr = new FileReader(src);
            fw = new FileWriter(dest);
            char[] c = new char[24];
            int len;//用于记录每次读取字符的数量,
            //3.读取字符到数组中
            while((len = fr.read(c)) != -1){
                //4.写入到文本文件中,此时字符存在数组c当中,循环一次读取24个字符
                fw.write(c,0,len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(fw != null){
                try {
                    fw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fr != null){
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    //读取一个文本文件到控制台
    @Test
    public void testFileReader(){
        //1.定义字符流对象
        FileReader fr = null;
        try {
            //2.定义文件对象
            File file = new File("file/hello.doc");
            fr = null;
            fr = new FileReader(file);
            char[] c = new char[24];
            int len;
            //3.把文件中的字符读入到字符数组中去
            while((len = fr.read(c)) != -1){
                //4.把字符数组转成字符串
                String str = new String(c,0,len);
                System.out.print(str);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(fr != null){
            try {
                fr.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
posted @ 2017-08-08 11:25  滕鹏飞  阅读(116)  评论(0编辑  收藏  举报