IO流(转换流的编码解码)

/*
 * 将一个中文字符串数据按照指定的编码表写入到一个文本文件中。
 * 
 * 
 * 注意:既然需要中已经明确了指定编码表的动作,
 * 那就不可以使用FileWriter ,因为FileWriter内部是使用默认的本地码表。
 * 只能使用其父类。OutputStreamWriter.
 * 
 * OutputStreamWriter接受一个字节输出流对象,既然是操作文件,那么该对象应该是FileOutputStream
 * 
 * OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("utf_3"),chartName);
 * 
 * 
 * 什么时候使用转换流呢?
 *  1,源或者目的对应的设备是字节流,但是操作的却是文本数据,可以使用转换流转为桥梁。
 *      提高对文本操作的便捷。
 * 
 *  2.一旦操作文本设计到具体的指定编码时,必须使用转换流。
 * */
public class Io30_1 {
public static void main(String[] args) throws Exception {
    writerText_2();
}
    public static void writerText_1() throws IOException{
        FileWriter fw=new FileWriter("gbk_1");
        fw.write("你好");
        fw.close();
    }

    public static void writerText_2() throws Exception, IOException{
        OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("gbk_3"),"GBK");
        FileWriter fw=new FileWriter("gbk_1");

        /*
         * 这两句代码的功能是等同的。
         * FileWriter:其实就是转换流指定了本机默认码表的体现而且这个转换流的子类对象,可以方便操作文本文件。
         *              简单说:操作文本的字节流+本机默认编码表
         *              这是按照默认码表来操作文件的便捷类。
         * 
         * 如果操作文本文件需要明确具体的码表,FileWriter ,就不行
         *  
         * */
    osw.write("你好");
    osw.close();
    }

    public static void writerText_3() throws IOException, Exception{
        OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream("utf_3"),"utf-8");
        osw.write("你好");
        osw.close();
    }



    public static void readText_1() throws IOException{
        FileReader fr=new FileReader("utf_3.txt");
        char[] buf=new char[1024];
        int len=fr.read(buf);
        String str=new String(buf,0,len);
        System.out.println(str);
        fr.close();
    }

    public static void readText_2() throws IOException, Exception{
        InputStreamReader isr=new InputStreamReader(new FileInputStream("utf_3.txt"),"utf-8");
        char[] buf=new char[1024];
        int len= isr.read(buf);
        String str=new String(buf,0,len);
        System.out.println(str);
         isr.close();
    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值