编码问题

来源:互联网 发布:java简明教程 pdf下载 编辑:程序博客网 时间:2024/06/04 19:47
package cn.itcast.io.p7.encode;


import java.io.IOException;
import java.io.UnsupportedEncodingException;


public class EncodeDemo {


/**
* @param args
* @throws IOException 
*/
public static void main(String[] args) throws IOException {


/*
* 字符串 --> 字节数组:编码。
* 字节数组 --> 字符串:解码。

* 你好:GBK:  -60 -29 -70 -61

* 你好: utf-8: -28 -67 -96 -27 -91 -67 


* 如果你编错了,解不出来。
* 如果编对了,解错了,有可能有救。
*/

String str = "谢谢";

byte[] buf = str.getBytes("gbk");

String s1 = new String(buf,"UTF-8");

System.out.println("s1="+s1);


byte[] buf2 = s1.getBytes("UTF-8");//获取源字节.

printBytes(buf2);//-17 -65 -67 -17 -65 -67 -17 -65 -67 
//-17 -65 -67 -17 -65 -67 -17 -65 -67 -17 -65 -67
//-48 -69 -48 -69 
String s2 = new String(buf2,"GBK");

System.out.println("s2="+s2);


// encodeDemo(str);



}


/**
* @param str
* @throws UnsupportedEncodingException
*/
public static void encodeDemo(String str)
throws UnsupportedEncodingException {
//编码;
byte[] buf = str.getBytes("UTF-8");

// printBytes(buf);

//解码:
String s1 = new String(buf,"UTF-8");

System.out.println("s1="+s1);
}


private static void printBytes(byte[] buf) {
for(byte b : buf){
System.out.print(b +" ");
}
}


}


——————————————————————————————————————————————————————————

package cn.itcast.io.p7.encode;


import java.io.IOException;




public class Test {


/**
* @param args
* @throws IOException 
*/
public static void main(String[] args) throws IOException {

String str = "ab你好cd谢谢";
// str = "ab琲琲cd琲琲";

// int len = str.getBytes("gbk").length;//gbk中字母1字节汉字2字节
// for(int x=0; x<len; x++){
// System.out.println("截取"+(x+1)+"个字节结果是:"+cutStringByByte(str, x+1));
// }

int len = str.getBytes("utf-8").length;//utf中字母和汉字都是2个字节
for(int x=0; x<len; x++){
System.out.println("截取"+(x+1)+"个字节结果是:"+cutStringByU8Byte(str, x+1));
}



// String str = "琲";
// byte[] buf = str.getBytes("gbk");
// for(byte b : buf){
// System.out.println(b);//-84  105 
// }

}

/*
  在java中,字符串“abcd”与字符串“ab你好”的长度是一样,都是四个字符。
但对应的字节数不同,一个汉字占两个字节。
定义一个方法,按照最大的字节数来取子串。
如:对于“ab你好”,如果取三个字节,那么子串就是ab与“你”字的半个,
那么半个就要舍弃。如果去四个字节就是“ab你”,取五个字节还是“ab你”.


*/

public static String cutStringByU8Byte(String str, int len) throws IOException {

byte[] buf = str.getBytes("utf-8");

int count = 0;
for(int x=len-1; x>=0; x--){
if(buf[x]<0)
count++;
else
break;
}

if(count%3==0)
return new String(buf,0,len,"utf-8");
else if(count%3==1)
return new String(buf,0,len-1,"utf-8");
else 
return new String(buf,0,len-2,"utf-8");

}


public static String cutStringByByte(String str,int len) throws IOException{

byte[] buf = str.getBytes("gbk");

int count = 0;
for(int x=len-1; x>=0; x--){
if(buf[x]<0)
count++;
else
break;
}

if(count%2==0)
return new String(buf,0,len,"gbk");
else
return new String(buf,0,len-1,"gbk");
}
}




















0 0