字符编码转换问题

字符编码转换

 


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();

}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值