package Other;
import java.io.IOException;
public class CutByteDemo {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String s= "hello你好啊,我欣賞你hahah";
byte []buf = s.getBytes("GBK");
for(int i =1;i<=buf.length;i++){
System.out.println("截取"+i+"个字节后为"+cutByteByGBK(buf,i));
}
buf = s.getBytes("utf-8");
for(int i =1;i<=buf.length;i++){
System.out.println("截取"+i+"个字节后为"+cutByteByU8(buf,i));
}
}
public static String cutByteByU8(byte[] buf, int j) throws IOException {
int count = 0;
int i =0;
for(i = j-1 ; i >= 0 ; i--){
if(buf[i]<0)
count++;
else
break;
}
String s =null;
//因為UTF-8三個字節表示一個漢字
if(count%3 == 0)
s =new String(buf,0,j,"utf-8");
else if(count%3 == 1)
s= new String(buf,0,j-1,"utf-8");
else if(count%3 == 2)
s= new String(buf,0,j-2,"utf-8");
return s;
}
public static String cutByteByGBK(byte[] buf, int j) throws IOException {
int count = 0;
int i =0;
for(i = j-1 ; i >= 0 ; i--){
if(buf[i]<0)
count++;
else
break;
}
String s =null;
//因為GBK用兩個字節表示一個漢字
if(count%2 == 0)
s =new String(buf,0,j,"GBK");
else
s= new String(buf,0,j-1,"GBK");
return s;
}
}
结果:
截取1个字节后为h
截取2个字节后为he
截取3个字节后为hel
截取4个字节后为hell
截取5个字节后为hello
截取6个字节后为hello
截取7个字节后为hello你
截取8个字节后为hello你
截取9个字节后为hello你好
截取10个字节后为hello你好
截取11个字节后为hello你好啊
截取12个字节后为hello你好啊
截取13个字节后为hello你好啊,
截取14个字节后为hello你好啊,
截取15个字节后为hello你好啊,我
截取16个字节后为hello你好啊,我
截取17个字节后为hello你好啊,我欣
截取18个字节后为hello你好啊,我欣
截取19个字节后为hello你好啊,我欣賞
截取20个字节后为hello你好啊,我欣賞
截取21个字节后为hello你好啊,我欣賞你
截取22个字节后为hello你好啊,我欣賞你h
截取23个字节后为hello你好啊,我欣賞你ha
截取24个字节后为hello你好啊,我欣賞你hah
截取25个字节后为hello你好啊,我欣賞你haha
截取26个字节后为hello你好啊,我欣賞你hahah
截取1个字节后为h
截取2个字节后为he
截取3个字节后为hel
截取4个字节后为hell
截取5个字节后为hello
截取6个字节后为hello
截取7个字节后为hello
截取8个字节后为hello你
截取9个字节后为hello你
截取10个字节后为hello你
截取11个字节后为hello你好
截取12个字节后为hello你好
截取13个字节后为hello你好
截取14个字节后为hello你好啊
截取15个字节后为hello你好啊
截取16个字节后为hello你好啊
截取17个字节后为hello你好啊,
截取18个字节后为hello你好啊,
截取19个字节后为hello你好啊,
截取20个字节后为hello你好啊,我
截取21个字节后为hello你好啊,我
截取22个字节后为hello你好啊,我
截取23个字节后为hello你好啊,我欣
截取24个字节后为hello你好啊,我欣
截取25个字节后为hello你好啊,我欣
截取26个字节后为hello你好啊,我欣賞
截取27个字节后为hello你好啊,我欣賞
截取28个字节后为hello你好啊,我欣賞
截取29个字节后为hello你好啊,我欣賞你
截取30个字节后为hello你好啊,我欣賞你h
截取31个字节后为hello你好啊,我欣賞你ha
截取32个字节后为hello你好啊,我欣賞你hah
截取33个字节后为hello你好啊,我欣賞你haha
截取34个字节后为hello你好啊,我欣賞你hahah