Java--转换流(处理流)

转换流的使用

举个例子说明:当我们的文件里面含有中文英文数字是,我们使用字节流将文件内容在内存中显示,英文和数字显示正常,而中文却却显示乱码。
这时候我们可以使用转换流将其转化为字符流显示在内存中。

1,处理流:转换流的使用

2,转换流:属于字符流

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

3, 作用:提供字节流与字符流之间的转换

  • 解码:字节,字节数组–》字符,字符数组
  • 编码:字符,字符数组–》字节,字节数组

4,字符集的使用

	@Test
    public void test1(){
        InputStreamReader isr= null;
        try {
            FileInputStream fis=new FileInputStream(new File("hello_gbk.txt"));

            //InputStreamReader sr=new InputStreamReader(fis);//使用系统默认的字符集
            //参数二指明字符集具体使用哪个字符集取决于文件.txt保存时使用哪个字符集
            isr = new InputStreamReader(fis,"utf-8);

            char[] cbuf=new char[1024];
            int len;
            while((len=isr.read(cbuf))!=-1){
                for(int i=0;i<len;i++) {
                    System.out.print(cbuf[i]);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (isr!=null)
                    isr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

因为转换流是处理流,所以它作用于原有的流上。

字符集:utf-8,gbk…
当一个文本文件时以utf-8字符集存储时,我们使用gbk字符集去转换会查看到乱码,所以要清楚看查看文本内容,要转换为文件保存时使用的字符集


接下来,我们使用InputStreamReaderOutputStreamWriter将一个文本文件(使用的是utf-8的字符集),复制成一个使用gbk字符的的文本文件:


    /**
     * 综合使用InputStreamReader和OutputStreamWriter
     */
    @Test
    public void tesr2(){

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

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

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

            char[] cbuf=new char[1024];
            int len;
            while((len=isr.read(cbuf))!=-1){
                for(int i=0;i<len;i++) {
                    osw.write(cbuf[i]);
                }
            }
        } 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();
            }
        }
    }

InputStreamReader是读入操作,所以要使用读入文本文件相对应的字符集。
OutputStreamWriter是写入操作,所以第二参数是要使用的字符集去写入一个文本文件。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值