Java的编码转换流

Java的编码转换流

  • OutputStreamWriter

    • OutputStreamWriter(OutputStream out)把传入的字节流转成字符流
    • OutputStreamWriter(OutputStream out ,String charsetName)把Unicode转成其他编码输出
  • InputStreamReader

    • InputStreamReader(InputStream in) 把传入的字节流转成字符流
    • InputStreamReader(InputStream in,String charsetName)读取其他编码转成Unicode
package com.cnblogs;

import java.io.*;

/*
本类用于测试编码转换流
 */
public class TestEncode {
    public static void main(String[] args) {
//        f1();
        f2();
    }

    private static void f1() {
        OutputStreamWriter out = null;
        try {
//            out = new OutputStreamWriter(new FileOutputStream("1.txt"),"iso-8859-1");//????&???
//            out = new OutputStreamWriter(new FileOutputStream("1.txt"),"gbk");//���౦��&�ɴ���
            out = new OutputStreamWriter(new FileOutputStream("1.txt"),"utf-8");//海绵宝宝&派大星
            /*
            一定要保证保存和打开时间使用的是同一张码表,就不会出现乱码的问题
             */
            out.write("海绵宝宝&派大星");
            System.out.println("执行成功!");
        } catch (Exception e) {
            System.out.println("执行失败!");
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void f2() {
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(new FileInputStream("1.txt"));//默认utf-8
//            in = new InputStreamReader(new FileInputStream("1.txt"),"gbk");
//            in = new InputStreamReader(new FileInputStream("1.txt"),"iso-8859-1");
//            System.out.println(in.read());//28023
//            System.out.println(in.read());//23092       read返回的是int类型
            //读取中文内容并且打印
            char[] ch = new char[8192];
            int len = in.read(ch);
            System.out.println(new String(ch,0,len));//utf-8   海绵宝宝&派大星
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

posted @ 2021-07-17 16:50  贪玩的阿柒  阅读(152)  评论(0编辑  收藏  举报