转载自https://blog.csdn.net/qy924120316/article/details/77185466
byte[]转String可通过如下:
String str = new String(byte[]);
转化之后可能会出现乱码的问题。
编码规范不一样。举个栗子,比如GB2312规范的中文“当”字,就是用0xB5,0xB1这两个八位的数字来表示的。在英文系统上,没有GB2312编码表,给他一个0xB5,0xB1,他就傻傻的当作ASCII来处理。放到Java里,他又会按照自己的UNICODE规范来处理,所以规范不一样,就会出现奇怪的结果,也就是乱码。
那么我们怎么解决byte[ ]转String的乱码问题呢?
这里推荐使用Base64
public class Base64Utils {
/**
* 转为Base64字符串
*
* @param input
* @return
*/
public static String toBase64(byte[] input) {
return android.util.Base64.encodeToString(input, android.util.Base64.NO_WRAP);
}
/**
* 转为Base64字符串
*
* @param input
* @return
*/
public static String toBase64(byte[] input, int flags) {
return android.util.Base64.encodeToString(input, flags);
}
/**
* 将Base64数据解码
*
* @param input
* @return
*/
public static byte[] fromBase64(byte[] input) {
return android.util.Base64.decode(input, android.util.Base64.DEFAULT);
}
/**
* 将Base64数据解码
*
* @param input
* @return
*/
public static byte[] fromBase64(byte[] input, int flags) {
return android.util.Base64.decode(input, flags);
}
/**
* 将Base64字符串解码
*
* @param input
* @return
*/
public static byte[] fromBase64String(String input) {
return android.util.Base64.decode(input, android.util.Base64.DEFAULT);
}
/**
* 将Base64字符串解码
*
* @param input
* @return
*/
public static byte[] fromBase64String(String input, int flags) {
return android.util.Base64.decode(input, flags);
}
}
这样就可以保证byte[]和String之间的标准转换了,网络传输的时候也不会出现意外。学习一下吧。
网友评论