侧边栏

JavaIO学习:转换流

转换流

1.涉及到的类

  • InputStreamReader:将InputStream转换为Reader
  • OutputStreamWriter:将Writer转换为OutputStream

 

2.构造器

  • public OutputStreamWriter(OutputStream out)
  • public OutputSreamWriter(OutputStream out,String charsetName)

3.作用

  • 提供字节流和字符流之间的转换

4.编码表:

常见的编码表:

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

示例:

复制代码
public void test2(){
       //1.造文件
       InputStreamReader isr = null;
       OutputStreamWriter osw = null;
       try {
           File file1 = new File("dbcp.txt");
           File file2 = new File("dbcp_gbk.txt");

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

           isr = new InputStreamReader(fis,"utf-8");
           osw = new OutputStreamWriter(fos,"gbk");
            //2.读写过程
           char[] cbuf = new char[20];
           int len;
           while ((len = isr.read(cbuf)) != -1){
               osw.write(cbuf,0,len);

           }
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           //3.关闭资源
           try {
               if (isr != null){
                   isr.close();
               }
           } catch (IOException e) {
               e.printStackTrace();
           }
           try {
               if (osw != null){
                   osw.close();
               }
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
}    
复制代码

 

posted @   菜鸟-传奇  阅读(560)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示