转换流
OutputStreamWriter
字符流转向字节流
作用: 可以根据不同编码格式写入
需要用到 FileOutputStream 类
可以使用不同编码格式写入
GBK表 是 Windows默认的 一个字占2个字节
UTF-8 是 Mac 默认的 一个字 占3个字节
InputStreamReader
字节流 转向 字符流
作用: 可以读取不同编码格式的文件
需要用到 FileInputStream 类
字符流转向字节流
字节流转向字符流
public class Demo {
public static void main(String[] args) throws IOException {
readGBK();
readUTF8();
readGBKByUTF8();
readUTF8ByGBK();
}
public static void getUTF8() throws IOException {
FileOutputStream fos = new FileOutputStream("/Users/s/Desktop/Test/UTF8.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos);
osw.write("扶大厦之将倾");
osw.close();
}
public static void getGBK() throws IOException {
FileOutputStream fos = new FileOutputStream("/Users/s/Desktop/Test/GBK.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
osw.write("挽狂澜之既倒");
osw.close();
}
public static void readUTF8() throws IOException {
FileInputStream fis = new FileInputStream("/Users/s/Desktop/Test/UTF8.txt");
InputStreamReader isr = new InputStreamReader(fis);
int len = 0;
char[] b = new char[1024];
while ((len = isr.read(b)) != -1) {
System.out.println(new String(b, 0, len));
}
isr.close();
}
public static void readGBK() throws IOException {
FileInputStream fis = new FileInputStream("/Users/s/Desktop/Test/GBK.txt");
InputStreamReader isr = new InputStreamReader(fis, "GBK");
int len = 0;
char[] b = new char[1024];
while ((len = isr.read(b)) != -1) {
System.out.println(new String(b, 0, len));
}
isr.close();
}
public static void readGBKByUTF8() throws IOException {
FileInputStream fis = new FileInputStream("/Users/s/Desktop/Test/GBK.txt");
InputStreamReader isr = new InputStreamReader(fis);
int len = 0;
char[] b = new char[1024];
while ((len = isr.read(b)) != -1) {
System.out.println(new String(b, 0, len));
}
isr.close();
}
public static void readUTF8ByGBK() throws IOException {
FileInputStream fis = new FileInputStream("/Users/s/Desktop/Test/UTF8.txt");
InputStreamReader isr = new InputStreamReader(fis,"GBK");
int len = 0;
char[] b = new char[1024];
while ((len = isr.read(b)) != -1) {
System.out.println(new String(b, 0, len));
}
isr.close();
}
}
Day.25
http://blog.csdn.net/ssssssue