|
Android中,String 与 byte[]数组可相互转化,不过转化过程中一定要注意字符编码的问题,否则会出现意想不到的问题,不啰嗦,上实例先
5 小时前 上传
下载附件 (1.51 MB)
主代码如下: String str1 = "eoe";
byte[]s1d1 = null;
byte[]s1d2 = null;
byte[]s1d3 = null;
try {
s1d1 = str1.getBytes("GBK");
s1d2 = str1.getBytes("UTF-8");
s1d3 = str1.getBytes("UTF-16LE");
String print1 = str1 + " getbytes(gbk) size = " + s1d1.length + "\n" +
str1 + " getbytes(UTF-8) size = " + s1d2.length + "\n" +
str1 + " getbytes(UTF-16LE) size = " + s1d3.length + "\n";
textview1.setText(print1);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str2 = "社区";
byte[]s2d1 = null;
byte[]s2d2 = null;
byte[]s2d3 = null;
try {
s2d1 = str2.getBytes("GBK");
s2d2 = str2.getBytes("UTF-8");
s2d3 = str2.getBytes("UTF-16LE");
String print2 = str2 + " getbytes(gbk) size = " + s2d1.length + "\n" +
str2 + " getbytes(UTF-8) size = " + s2d2.length + "\n" +
str2 + " getbytes(UTF-16LE) size = " + s2d3.length + "\n";
textview2.setText(print2);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str3 = "eoe社区";
byte[]s3d1 = null;
byte[]s3d2 = null;
byte[]s3d3 = null;
try {
s3d1 = str3.getBytes("GBK");
s3d2 = str3.getBytes("UTF-8");
s3d3 = str3.getBytes("UTF-16LE");
String print3 = str3 + " getbytes(gbk) size = " + s3d1.length + "\n" +
str3 + " getbytes(UTF-8) size = " + s3d2.length + "\n" +
str3 + " getbytes(UTF-16LE) size = " + s3d3.length + "\n";
textview3.setText(print3);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ;
}
try {
String new1 = new String(str3.getBytes("GBK"), "GBK");
String new2 = new String(str3.getBytes("GBK"), "UTF-8");
String new3 = new String(str3.getBytes("GBK"), "UTF-16LE");
String print4 = "new string(" + str3 + ".getbytes('gbk')), 'gbk') = " + new1 + "\n" +
"new string(" + str3 + ".getbytes('gbk')), 'utf-8') = " + new2 + "\n" +
"new string(" + str3 + ".getbytes('gbk')), 'utf-16le') = " + new3 + "\n";
textview4.setText(print4);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return ;
}
本例举例三种常用的字符编码”GBK" "UTF-8" "UTF-16LE"
我们发现,在使用String.getBytes这个方法时,
若字符编码参数使用”GBK“
则遇字母占一个字节,遇中文占两个字节
若字符编码参数使用”UTF-8“
则遇字母占一个字节,遇中文占三个字节
若字符编码参数使用”UTF-16LE“
则无论字母或中文均占两个字节
反之使用new String根据byte数组构造字符串对象时,需要根据byte[]数组所使用的字符编码进行相应转化
否则容易出现乱码,正如下图所示:
5 小时前 上传
下载附件 (331.08 KB)
很多童鞋都使用默认的编码参数,所以就可能导致一些奇奇怪怪的问题,所以大家要注意咯下面附上源码 |
|