专注于 JetBrains IDEA 全家桶,永久激活,教程
持续更新 PyCharm,IDEA,WebStorm,PhpStorm,DataGrip,RubyMine,CLion,AppCode 永久激活教程

转换流

转换流

概念

转换流是处理流的一种

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

70_1.png

转换流分类

  • 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();
    }
}

未经允许不得转载:搜云库技术团队 » 转换流

JetBrains 全家桶,激活、破解、教程

提供 JetBrains 全家桶激活码、注册码、破解补丁下载及详细激活教程,支持 IntelliJ IDEA、PyCharm、WebStorm 等工具的永久激活。无论是破解教程,还是最新激活码,均可免费获得,帮助开发者解决常见激活问题,确保轻松破解并快速使用 JetBrains 软件。获取免费的破解补丁和激活码,快速解决激活难题,全面覆盖 2024/2025 版本!

联系我们联系我们