java里面byte数组和String字符串怎么转换

如题所述

Java中byte数组转换成string字符串可以直接使用string类的构造函数。而string转byte数组,则可以使用string类型的getBytes()方法进行转换,如下形式:
1、string 转 byte[]
String str = "Hello";//声明一个字符串
byte[] srtbyte = str.getBytes();//使用string类的getBytes方法进行转换
2、byte[] 转 string
byte[] srtbyte;//声明一个byte字节数组
String res = new String(srtbyte);//使用构造函数转换成字符串
System.out.println(res);
也可以将byte转换的时候,设定编码方式相互转换,如下代码:

String str = "hello";
byte[] srtbyte = null;
try {
srtbyte = str.getBytes("UTF-8");//设定转换的编码格式
String res = new String(srtbyte,"UTF-8");
System.out.println(res);
} catch (UnsupportedEncodingException e) {//有可能会出现不能支持的编码格式,捕捉异常。
e.printStackTrace();
}
温馨提示:答案为网友推荐,仅供参考