首页 > 其他 > 详细

转换流

时间:2020-08-08 21:17:09      阅读:66      评论:0      收藏:0      [点我收藏+]

转换流

概念

转换流是处理流的一种

转化流提供了在字节流和字符流之间的转换

技术分享图片

转换流分类

  • InputStreamReader:将一个字节的输入流转换为字符的输入流
  • OutputStreamWriter:将一个字符的输出流转换为字节的输出流

字符集

  • ASCII: 美国标准信息交换码,用一个字节的7位可以表示
  • ISO8859-1: 拉丁码表、欧洲码表,用一个字节的8位表示
  • GB2312: 中国的中文编码表,最多两个字节编码
  • GBK: 中国的中文编码表升级,融合了更多的中文文字符号,最多两个字节编码
  • Unicode: 国际标准码,融合了目前人类使用的所有字符,为每一个字符分配唯一的字符码,所有的文字都用两个字节来表示
  • UTF-8: 变长的编码方式,可用1-4个字节来表示字符

使用

InputStreamReader

  • 实现将字节的输入流按指定字符集转换为字符的输入流。
  • 需要和InputStream“套接”

利用到的构造器

InputStreamReader isr = new InputStreamReader(InputStream in,String charsetName);

参数二指明了字符集,具体使用哪种字符集取决于文件保存时使用的字符集

举例:

InputStreamReader isr = new InputStreamReader(fis);//使用系统默认的字符集

InputStreamReader isr = new InputStreamReader(fis,"UTF-8");//使用UTF-8字符集

OutputStreamWriter

  • 实现将字符的输出流按指定字符集转换为字节的输出流。
  • 需要和OutputStream“套接”

利用到的构造器

public OutputStreamWriter(OutputStream out, String charsetName)

举例

osw = new OutputStreamWriter(fos,"gbk");

代码实现

InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
    File file1 = new File("hello.txt");
    File file2 = new File("hi.txt");

    FileInputStream fis = new FileInputStream(file1);
    FileOutputStream fos = new FileOutputStream(file2);

    isr = new InputStreamReader(fis,"UTF-8");
    osw = new OutputStreamWriter(fos,"gbk");

    char[] cbuf = new char[20];
    int len;
    while((len = isr.read(cbuf)) != -1){
        osw.write(cbuf,0,len);
    }
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if(isr != null)
            isr.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        if(osw != null)
            osw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

转换流

原文:https://www.cnblogs.com/CrabDumplings/p/13459733.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!