1、字符串中的编码与解码:
编码:
String s = "中国";
byte[] bytes = s.getBytes("GBK");
解码:
String ss = new String(bytes,"GBK");
//String ss = new String(bytes, 0, len);
System.out.print(ss);
//System.out.println(Arrays.toString(bytes));结果为byte类型的数组
2、字符流中的编码与解码:
字符流抽象基类:Reader/writer,其子类InputStreamReader/OutputStreamWriter,分别是字节流到字符流和字符流到字节流的桥梁。
编码
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(fileName),"GBK");//按GBK编码
String s = "中国风";
osw.write(s);//把“中国风”编码进 fileName
osw.close();
解码
InputStreamReader isr = new InputStreamReader(new FileInputStream(fileName),"GBK");//按GBK解码
char[] chars = new char[1024];
int len = 0;
while ((len = isr.read(chars)) != -1){
//把字符数组chars转化成字符串:
String s = new String(chars, 0, len);
System.out.print(s));//输出解码后的结果:中国风
}
isr.close();