javaIO流中的转换流

转换流的作用,主要是为了解决数据在传输过程中,因系统环境的不同造成的乱码情景,造成乱码的原因,是因为存储时的编码方式和解码时候的编码方式不一致所导致的。
会有以下一些情况,例如:
比如存储在客户端本地的记事本文件,a.txt中存储了3个汉字(GBK编码),那么这个时候其是2*3=6个字节,理想情况下在数据传输过程中,中间不会转换为其他的编码方式,服务器的编码方式是是UTF-8,会把6个字节转化为2个汉字,当然是错误的。

字符输入流 : InputStreamReader类

构造方法

public InputStreamReader(InputStream in) : 使用默认编码进行解析数据
public InputStreamReader(InputStream in,String charsetName) : 用指定的编码进行解析数据

字符输出流 : OutputStreamWriter类

构造方法

public OutputStreamWriter(OutputStream out) : 根据默认编码把字节流的转换为字符流对象
public OutputStreamWriter(OutputStream out,String charsetName) : 根据指定编码把字节流对象转换为字符流对象

网络编程章节, 还有别的用处

案例 :

桌面上有一个文件:a.txt (GBK)
要求:把a1.txt变成 UTF-8的编码格式

public class InputStreamReadTest {
    public static void main(String[] args) throws IOException {
        //读取本地GBK文件a.txt,生成一个字符流
        FileInputStream fileInputStream = new FileInputStream("Features_IO/src/com/ligong/a.txt");
        InputStreamReader isr=new InputStreamReader(fileInputStream,"gbk");
        BufferedReader bf=new BufferedReader(isr);
        //准备向文件中写入一个UTF编码方式字符流。
        FileOutputStream fileOutputStream = new FileOutputStream("Features_IO/src/com/ligong/a1.txt");
        OutputStreamWriter osw=new OutputStreamWriter(fileOutputStream,"UTF-8");
        BufferedWriter bw=new BufferedWriter(osw);
        String line ;
        while (( line = bf.readLine())!=null){
            bw.write(line);
            bw.newLine();
            bw.flush();
        }
        bw.close();
        bf.close();
    }
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Code攻城狮

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值