- 通过String类转换
//Original String String string = "hello world"; //Convert to byte[] byte[] bytes = string.getBytes(); //Convert back to String String s = new String(bytes); //Check converted string against original String System.out.println("Decoded String : " + s);
这种方式使用平台默认字符集
- 通过Base64转换
Java 8 开始可以使用Base64类
//Original byte[] byte[] bytes = "hello world".getBytes(); //Base64 Encoded String encoded = Base64.getEncoder().encodeToString(bytes); //Base64 Decoded byte[] decoded = Base64.getDecoder().decode(encoded); //Verify original content System.out.println( new String(decoded) );