转换流:
转换流提供了在字节流和字符流之间的转换,用于将字节流的读入转换为字符流的读入,将字符流的写出转换为字节流的写出,包括InputStreamReader和OutputStreamWriter,其中:
- InputStreamReader:将InputStream转换为Reader,它有两类构造方法:
- public InputStreamReader(InputStream in) :使用系统默认字符集
- public InputSreamReader(InputStream in,String charsetName):指定字符集
- OutputStreamWriter:将Writer转换为OutputStream,它也有两类构造方法:
- public OutputStreamWriter(OutputStream out) :使用系统默认字符集
- public OutputStreamWriter(OutputStream out,String charsetName):指定字符集
例:将“Hello.txt”文件在控制台打印出来,并将其以gbk编码格式存入“Hello-gbk.txt”文件中
package cn.jingpengchong.io;
import java.io.*;
public class Test {
public static void main(String[] args) {
String src = "Hello.txt";
String des = "Hello-gbk.txt";
test(src,des);
}
private static void test(String src, String des) {
//第二个参数为指定的字符集,如果省略了则使用系统默认的字符集,具体使用何种字符集取决于保存文件时使用的字符集
InputStreamReader reader= null;
OutputStreamWriter writer = null;
try {
reader = new InputStreamReader(new FileInputStream(src),"utf-8");
writer = new OutputStreamWriter(new FileOutputStream(des), "gbk");
char[] data = new char[10];
int read = reader.read(data);
while (read != -1){
String str = new String(data,0,read);
System.out.print(str);
writer.write(data,0,read);
read = reader.read(data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(reader != null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(writer != null){
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
运行结果如下:
此时如果以UTF-8格式打开“Hello-gbk.txt”文件,则会出现乱码: