面试问到如何用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 {加入Java开发交流君样:484138291一起吹水聊天
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 {加入Java开发交流君样:484138291一起吹水聊天
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();
}
}
}
}
分类: [java]
最新2021整理收集的很多干货,包含mysql,netty,spring,线程,spring cloud、jvm、源码、算法等详细讲解等。【获取资料】