Java的编码转换流

2021/7/17 17:06:18

本文主要是介绍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();
            }
        }
    }
}



这篇关于Java的编码转换流的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程