字符编码转换
public class TransferStreamDemo2 {
//读/
@Test//用默认编码(MyEclipse平台设置的编码)---依赖平台的编码
public void readTextDecoding() throws IOException{
FileReader fr=new FileReader("file\\gbk.txt");
char cbuf[]=new char[128];
int len=0;
while((len=fr.read(cbuf))!=-1){
String str=new String(cbuf,0,len);
System.out.println(str);
}
fr.close();
}
@Test//用转换流指定编码去读--与平台的编码无关
//FileInputStream+指定编码+InputStreamReader(in,“utf8”)
public void readTextDecoding2() throws IOException{
FileInputStream in=new FileInputStream("file\\utf8.txt");
InputStreamReader rd=new InputStreamReader(in,"utf8");//指定读取文件的编码方式
char[] cbuf=new char[128];
int len=0;
while((len=rd.read(cbuf))!=-1){
String str=new String(cbuf,0,len);
System.out.println(str);
}
rd.close();
}
/*
* 用String的构造函数解决IO流中的乱码问题
* FileInputStream+new String(bs,“gbk”)
* 缺陷:截取字节数据时,不要把一个完整的汉字拆开会乱码
* */
@Test
public void readTextDemo3() throws IOException{
FileInputStream file=new FileInputStream("file\\gbk.txt");
byte buf[]=new byte[128];//存在拆分错误
int len=0;
while((len=file.read(buf))!=-1){
String str=new String(buf,0,len,"gbk");
System.out.println(str);
}
file.close();
}
///写/
@Test//FileWrite:FileOutputStream+默认编码方式
public void writeTextEncoding() throws IOException{
FileWriter out=new FileWriter("file\\utf-8_2.txt");
out.write("每天进步一点点.....hhhhh");
out.close();
}
@Test//OutputStreamWrite+FileOutputStream+默认编码
public void writeTextEncoding2() throws IOException{
OutputStreamWriter sw=new OutputStreamWriter(new FileOutputStream("file\\utf-8_2.txt"));
sw.write("lallalalalallalal");
sw.close();
}
※※※采用转换流以指定编码方式写※※※※
@Test//OutputStreamWriter + FileOutputStream +指定编码表
public void writeTextEncoding3() throws IOException{
OutputStreamWriter sw=new OutputStreamWriter(new FileOutputStream("file\\gbk2.txt"),"gbk");
sw.write("lallalalalallalal");
sw.close();
}
}