转换流总结及注意点

本文介绍了如何使用转换流将字节流转为字符流,并演示了具体的转码过程,包括从GBK编码到UTF-8编码的转换步骤。同时,还强调了在进行文件内容读取和转码操作时需要注意的细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、转换流的使用

    1.将字节流转为字符流:

FileInputStream fis = new FileInputStream("字节流文件");
InputStreamReader isr = new InputStreamReader(fis);
char[] c = new char[1024];
int len = 0;
while((len = isr.read(c)) != -1){
System.out.println(new String(c,0,len));
}
isr.close();
fis.close();

    2.转码:

FileInputStream fis = new FileInputStream("gbk格式文件");
InputStreamReader isr = new InputStreamReader(fis,"gbk");

FileOutputStream fos = new FileOutputStream("utf-8格式文件");
OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");

char[] c = new char[1024];
int len = 00;
while((len = isr.read(c)) != -1){
osw.write(new String(b,0,len));
}

osw.close();
isr.close();
fos.close();
fis.close();

    3.注意点:

            1)读取文件内容是,输入流的格式必须跟输出流顺序的编码格式一致

            2)转码的InputStreamReader形参传的编码与文件编码格式相同

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值