2021-08-07 编码转化流复习
程序员文章站
2022-06-16 21:35:53
...
编码转换流
字节流:针对的是二进制文件
字符流:针对文本文件,读写容易出现乱码的现象,在读写时,最好指定编码集为UTF-8
编码转换流InputStreamReader/OutputStreamWriter)主要进行编码的转换,用来解决字符流读写乱码!!!
OutputStreamWriter :
OutputStreamWriter(OutputStream out)把传入的字节流转成字符流
OutputStreamWriter(OutputStream out ,String charsetName)把Unicode转成其他编码输出
InputStreamReader :
InputStreamReader(InputStream in) 把传入的字节流转成字符流
InputStreamReader(InputStream in,String charsetName)读取其他编码转成Unicode
package cn.tedu.test2;
import java.io.*;
import java.util.Arrays;
public class Testt {
public static void main(String[] args) {
method();
method1();
}
private static void method() {//需求:读取1.txt中的中文内容,并且打印在控制台
InputStreamReader in=null;
try {
in=new InputStreamReader(new FileInputStream("D://ready/2.txt"),"utf-8");
char[] chars=new char[100];
int read = in.read(chars);
System.out.println(Arrays.toString(chars));
System.out.println(chars);
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static void method1() {
OutputStreamWriter out=null;
try {
out=new OutputStreamWriter(new FileOutputStream("D://ready/2.txt"),"utf-8");
out.write("ss");
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
推荐阅读