Java解决字节流乱码问题

时间:2021-07-20
本文章向大家介绍Java解决字节流乱码问题,主要包括Java解决字节流乱码问题使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1. 转换流

  • InputStreamReader
  • OutputStreamWriter

2. InputStreamReader 类

转换流java.io.InputStreamReader,是Reader的子类,是从字节流到字符流的桥梁。它读取字节,并使用指定的字符集将其解码为字符。它的字符集可以由名称指定,也可以接受平台的默认字符集。

构造方法

  • InputStreamReader(InputStream in): 创建一个使用默认字符集的字符流。
  • InputStreamReader(InputStream in, String charsetName): 创建一个指定字符集的字符流。

3. OutputStreamWriter 类

转换流java.io.OutputStreamWriter ,是Writer的子类,是从字符流到字节流的桥梁。使用指定的字符集将字符编码为字节。它的字符集可以由名称指定,也可以接受平台的默认字符集。

构造方法

  • OutputStreamWriter(OutputStream in): 创建一个使用默认字符集的字符流。
  • OutputStreamWriter(OutputStream in, String charsetName): 创建一个指定字符集的字符流。

4. 读取文件

使用转换流设置读取编码为UTF-8
InputStreamReader isr = new InputStreamReader(new FileInputStream("a.txt"),"UTF-8");

package com.se.file;

import java.io.*;

public class Demo06_Fis_乱码 {
    public static void main(String[] args) {
        BufferedReader bfr = null;
        try {
            InputStreamReader isr = new InputStreamReader(new FileInputStream("F:\\Demo1\\w.txt"), "UTF-8");
            bfr = new BufferedReader(isr);
            String str = "";
            while ((str = bfr.readLine()) != null) {
                System.out.println(str);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bfr != null)
                    bfr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

5. 写入文件

使用转换流设置读取编码为UTF-8

OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("F:\\Demo1\\a.txt"), "UTF-8");

package com.se.file;

import java.io.*;

public class Demo06_Fis_乱码 {
    public static void main(String[] args) {
        BufferedWriter bfw = null;
        try {
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("F:\\Demo1\\a.txt"), "UTF-8");
            bfw = new BufferedWriter(osw);
            bfw.write("你好");
            bfw.write("\r\n");
            bfw.write("abc");
            bfw.write("\r\n");
            bfw.flush();
            bfw.write("哈哈哈");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bfw != null)
                    bfw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

原文地址:https://www.cnblogs.com/LEPENGYANG/p/15035266.html