编码转换流
字节流:针对二进制文件
字符流:针对文本文件,读写容易出现乱码的现象,在读写时,最好指定编码集为UTF-8
概述
编码转换流(InputStreamReader/OutputStreamWriter
)主要进行编码的转换,用来解决字符流读写乱码的问题
使用的工具API
OutputStreamWriter :
OutputStreamWriter(OutputStream out)
把传入的字节流转成字符流OutputStreamWriter(OutputStream out ,String charsetName)
把Unicode转成其他编码输出
InputStreamReader :
InputStreamReader(InputStream in)
把传入的字节流转成字符流InputStreamReader(InputStream in,String charsetName)
读取其他编码转成Unicode
常见字符编码表
示例代码
package cd.tedu.encoding;
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
* 编码转换测试
*/
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"),"gbk");
//out = new OutputStreamWriter(new FileOutputStream("1.txt"), StandardCharsets.ISO_8859_1);
out = new OutputStreamWriter(new FileOutputStream("1.txt"), StandardCharsets.UTF_8);
out.write("一拳超人&鬼灭之刃");
System.out.println("成功");
} catch (Exception e) {
System.out.println("失败");
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
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"));
//in = new InputStreamReader(new FileInputStream("1.txt"),"gbk");
//in = new InputStreamReader(new FileInputStream("1.txt"), StandardCharsets.ISO_8859_1);
in = new InputStreamReader(new FileInputStream("1.txt"), StandardCharsets.UTF_8);
//System.out.println(in.read());
char[] ch = new char[8192];
int len = in.read(ch);
System.out.println(new String(ch,0,len));
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}