zoukankan      html  css  js  c++  java
  • java 21

    既然字节流可以复制文件,那么字符流当然也有。

    同样的思路: 

    数据源:
        a.txt -- 读取数据 -- 字符转换流 -- InputStreamReader
    目的地:
        b.txt -- 写出数据 -- 字符转换流 -- OutputStreamWriter

     1         // 封装数据源
     2         InputStreamReader isr = new InputStreamReader(new FileInputStream(
     3                 "a.txt"));
     4         // 封装目的地
     5         OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
     6                 "b.txt"));
     7 
     8         // 读写数据
     9         // 方式1
    10         // int ch = 0;
    11         // while ((ch = isr.read()) != -1) {
    12         // osw.write(ch);
    13         // }
    14 
    15         // 方式2
    16         char[] chs = new char[1024];
    17         int len = 0;
    18         while ((len = isr.read(chs)) != -1) {
    19             osw.write(chs, 0, len);
    20             // osw.flush();
    21         }
    22 
    23         // 释放资源
    24         osw.close();
    25         isr.close();

    简化:

      我们常用的编码表大都是使用本地默认的编码表,也就是GBK。所以呢,我们可以不指定编码表。

    同时,字符流的名称有些长...好长,所以呢,Java就提供了字符流的子类给我们使用:

    之前用的字符流:

      OutputStreamWriter = FileOutputStream + 编码表(GBK)

      InputStreamReader = FileInputStream + 编码表(GBK)

    使用它的子类:

      FileWriter = FileOutputStream + 编码表(GBK)

      FileReader = FileInputStream + 编码表(GBK)

    来,使用简化版重新做复制:

     1         //封装数据源
     2         FileReader fr = new FileReader("a.txt");
     3         //封装目的地
     4         FileWriter fw = new FileWriter("b.txt");
     5         
     6         //使用一次读取一个字符数组的方式来复制
     7         int len = 0;
     8         char[] ch = new char[1024];
     9         while((len = fr.read(ch)) != -1){
    10             fw.write(ch,0,len);
    11         }
    12         //释放资源
    13         fw.close();
    14         fr.close();
    15     }

      代码少了很多,简洁明了

    何事都只需坚持.. 难? 维熟尔。 LZL的自学历程...只需坚持
  • 相关阅读:
    QT 信号槽 异步事件驱动 单线程 多并发
    Qt 静态库与共享库(动态库)共享配置的一个小办法
    关于:有符号与无符号整数的大小比较
    QT信号槽 中的对象野指针
    Qt程序打包发布
    Qt程序打包发布
    SQL Server 2012 sa 用户登录 18456 错误 (转)
    QtCreator常用之快捷键
    opengl中相关的计算机图形变换矩阵之:模型视图几何变换
    opengl中相关的计算机图形变换矩阵之:齐次坐标 (摘编)
  • 原文地址:https://www.cnblogs.com/LZL-student/p/5926143.html
Copyright © 2011-2022 走看看