String与byte[]互转,每次用,每次查,觉得还是总结一下,加深记忆比较好,看代码一看便知:
import java.io.UnsupportedEncodingException;
public class StringByteTest{
public static void main(String[] args){
String hello = "hello";
byte[] helloBytes = hello.getBytes();
System.out.println("helloBytes:" + helloBytes);
String str = new String(helloBytes);
System.out.println("str:" + str);
try {
String str2 = new String(helloBytes, "UTF-8");
System.out.println("str2:" + str2);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (helloBytes != null && helloBytes.length > 0) {
StringBuilder stringBuilder = new StringBuilder();
for (byte b : helloBytes) {
stringBuilder.append(String.format("%X", b));
}
System.out.println("hello hex:" + stringBuilder);
}
}
}
结果:
