转换流:字符流和字节流之间的桥梁
用于处理程序的编码问题
OutputStreamWriter类:字符转字节流
写文本文件:
package demo; import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter; public class Demo {
public static void main(String[] args) throws IOException {
writeGBK();
writeUTF8();
} public static void writeGBK() throws IOException {
FileOutputStream fos = new FileOutputStream("d:\\gbk.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
osw.write("你好");// gbk的一个汉字是2个字节
osw.close();
} public static void writeUTF8() throws IOException {
FileOutputStream fos = new FileOutputStream("d:\\utf8.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
osw.write("你好");// utf8的一个汉字是3个字节
osw.close();
}
}
InputStreamReader类:
字节转字符流过程:
这里读取上面写的文本文件:
package demo; import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader; public class Demo {
public static void main(String[] args) throws IOException {
readGBK();
readUTF8();
} public static void readGBK() throws IOException {
FileInputStream fis = new FileInputStream("d:\\gbk.txt");
InputStreamReader isr = new InputStreamReader(fis);
char[] ch = new char[1024];
int len = isr.read(ch);
System.out.println(new String(ch, 0, len));
} public static void readUTF8() throws IOException {
FileInputStream fis = new FileInputStream("d:\\utf8.txt");
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
char[] ch = new char[1024];
int len = isr.read(ch);
System.out.println(new String(ch, 0, len));
}
}
这里注意,如果编码集和读取问文本不一致,就会发生乱码或者输出?的问题