分类分类
关注+2010-01-21作者:
现在有一段程序,大概是这样的:
对输入的字符串str处理:byte[] bb = str.getBytes(),获得的字节数组存进一个ByteBuffer。另有一个线程不定期地从Bytebuffer里取出长度不定的字节,打包后由信号传输设备传输到另一台电脑,收到包后再解析。
现在的问题是对英文字符串处理没问题,但中文的不定期出乱码。我觉得是编码的问题。用GB2312编码,getBytes()处理后英文字符对应一个字节,中文的是两个。放到ByteBuffer里后,截取时可能刚好把中文的两个字节分开到两个包里了。因为传输后对每个包的解析是单独进行的,直接处理,没有再把字节取出来缓存后再处理,所以会出现乱码。
所以我的想法是,能不能判断ByteButter里我要截取的字节数组末尾的那个字节是英文的还是中文的字符产生的。是英文的我就不处理,是中文的就分情况处理。
哪位能给我想个办法,谢谢~
我简单做了一个。。用GBK字符库的char[],代替byte[]
public class strdeal {
public String getString(){//输入字符串
System.out.println("input string");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String s="";
try {
s = br.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println(s);//可以直接打印字符串
return s;
}
public byte[] getByet(String s){//字符串转为byte[]
byte[] bb = s.getBytes();
return bb;
}
private char[] getChars (byte[] bytes) {//byte转为char[],使用GBK
Charset cs = Charset.forName ("GBK");
ByteBuffer bb = ByteBuffer.allocate (bytes.length);
bb.put (bytes);
bb.flip ();
CharBuffer cb = cs.decode (bb);
return cb.array();
}
public static void main(String args[]){//简单测试
strdeal sdeal=new strdeal();
//System.out.println(sdeal.getString());
byte[] arrbyte=sdeal.getByet(sdeal.getString());
char[] arrchar=sdeal.getChars(arrbyte);
/*for(byte b:arrbyte){
System.out.print(b);
}*/
for(char c:arrchar){
System.out.print(c);
}
System.out.println();
String res=new String(arrbyte);
System.out.println(res);
}
}
/*输出
input string
ABC124不是么
ABC124不是么
*/
相关文章
更多+相同厂商
热门推荐
点击查看更多
点击查看更多
点击查看更多
说两句网友评论