黑马程序员
字符编码和字符集
编码引出的问题–FileReader读取GBK格式文件
转换流的原理
OutputStreamWriter介绍&代码实现
package IOCode;
import sun.nio.cs.ext.GBK;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class Code_Demo {
public static void main(String[] args) throws IOException {
To_utf_8();
To_gbk();
}
private static void To_utf_8() throws IOException {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream("F:\\杂七杂八\\a.txt", true));
outputStreamWriter.write("\r\n你好呀——utf_8");
outputStreamWriter.flush();
outputStreamWriter.close();
}
private static void To_gbk() throws IOException {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream("F:\\杂七杂八\\a.txt", true), "GBK");
outputStreamWriter.write("\r\n你好呀——GBK");
outputStreamWriter.flush();
outputStreamWriter.close();
}
}
OutputStreamReader介绍&代码实现
package IOCode;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class InputStreamReader_Demo {
public static void main(String[] args) throws IOException {
read_utf_8();
read_gbk();
}
private static void read_utf_8() throws IOException {
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("F:\\杂七杂八\\a.txt"));
int len=0;
char[] chars = new char[1024];
while ((len=inputStreamReader.read(chars))!=-1){
System.out.println(new String(chars,0,len));
}
System.out.println("*********************************");
// len=0;
// while ((len=inputStreamReader.read())!=-1){
// System.out.print((char)len);
// }
inputStreamReader.close();
}
private static void read_gbk() throws IOException {
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("F:\\杂七杂八\\a.txt"),"GBK");
int len=0;
char[] chars = new char[1024];
while ((len=inputStreamReader.read(chars))!=-1){
System.out.println(new String(chars,0,len));
}
System.out.println("*********************************");
// len=0;
// while ((len=inputStreamReader.read())!=-1){
// System.out.print((char)len);
// }
inputStreamReader.close();
}
}