原因:文件保存的编码和编码程序(如Eclipse或IDEA)里面项目的的编码集不一样,所以乱码,将文件和项目的编码集改为一样的,就可以了
@Test
public void test4() throws UnsupportedEncodingException{
//我项目的编码集是UTF-8
String s = “我爱中国”;
System.out.println(s);//我爱中国
byte[] bytes = s.getBytes(“GBK”);
System.out.println(Arrays.toString(bytes));//[-50, -46, -80, -82, -42, -48, -71, -6]
System.out.println(bytes);//[B@14514713
//在这里的bytes这个位置只能是变量,不是的话会报错
String s1 = new String(bytes,“GBK”);
System.out.println(s1);//我爱中国
String s2 = new String(bytes,“UTF-8”);
System.out.println(s2);//???й?
}
- 测试代码
@Test
public void test2() throws Exception{
//创建实例化FileReader对象
FileReader fr = new FileReader("E:\\testNomal\\FileTest\\三国演义3.txt");
int i = 0;
String mess = "";
while((i=fr.read()) != -1){
mess += (char)i;
//如果没有char的话,输出的是一长串数字
//6553365533655331016655336553349765533655336553365533108165533655336553365533140165533655331780655336553365533185565533881655336553365533655336553365533655336553365533655336553342356553365533
}
System.out.println(mess);
//仍然乱码:���ϸ��DZ����й����չ��۴���ܿ�ͱ�����������*#��
//原因:文件保存的编码和现在Eclipse里面的编码集不一样,所以乱码,将文件和项目的编码集改为一样的
fr.close();
}
当然也可以使用下面方法解决编码问题
解决编码问题
字符串
- 相关方法
方法名 | 说明 |
---|---|
byte[] getBytes() | 使用平台的默认字符集将该 String编码为一系列字节 |
byte[] getBytes(String charsetName) | 使用指定的字符集将该 String编码为一系列字节 |
String(byte[] bytes) | 使用平台的默认字符集解码指定的字节数组来创建字符串 |
String(byte[] bytes, String charsetName) | 通过指定的字符集解码指定的字节数组来创建字符串 |
@Test
public void test4() throws UnsupportedEncodingException{
//我项目的编码集是UTF-8
String s = "我爱中国";
System.out.println(s);//我爱中国
byte[] bytes = s.getBytes("GBK");
System.out.println(Arrays.toString(bytes));//[-50, -46, -80, -82, -42, -48, -71, -6]
System.out.println(bytes);//[B@14514713
//在这里的bytes这个位置只能是变量,不是的话会报错
String s1 = new String(bytes,"GBK");
System.out.println(s1);//我爱中国
String s2 = new String(bytes,"UTF-8");
System.out.println(s2);//????й?
}
字符流
-
字符流中和编码解码问题相关的两个类
-
InputStreamReader:是从字节流到字符流的桥梁
它读取字节,并使用指定的编码将其解码为字符
它使用的字符集可以由名称指定,也可以被明确指定,或者可以接受平台的默认字符集
-
OutputStreamWriter:是从字符流到字节流的桥梁
是从字符流到字节流的桥梁,使用指定的编码将写入的字符编码为字节
它使用的字符集可以由名称指定,也可以被明确指定,或者可以接受平台的默认字符集
-
-
构造方法
方法名 说明 InputStreamReader(InputStream in) 使用默认字符编码创建InputStreamReader对象 InputStreamReader(InputStream in,String chatset) 使用指定的字符编码创建InputStreamReader对象 OutputStreamWriter(OutputStream out) 使用默认字符编码创建OutputStreamWriter对象 OutputStreamWriter(OutputStream out,String charset) 使用指定的字符编码创建OutputStreamWriter对象
@Test
public void test5() throws Exception{
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("E:\\testNomal\\FileTest\\FileWriterTestUnic.txt"),"GBK");
osw.write("我爱中国");
osw.close();
InputStreamReader isr = new InputStreamReader(new FileInputStream("E:\\testNomal\\FileTest\\FileWriterTestUnic.txt"),"GBK");
//一次读取一个字符数据
int ch;
while ((ch=isr.read())!=-1) {
System.out.println((char)ch);
}
isr.close();
}
/*
我
爱
中
国
*/