经过用例学习Java中的byte数组和String互相转换,这种转换可能在不少状况须要,好比IO操做,生成加密hash码等等。java
除非以为必要,不然不要将它们互相转换,他们分别表明了不一样的数据,专门服务于不一样的目的,一般String表明文本字符串,byte数组针对二进制数据数组
用String.getBytes()方法将字符串转换为byte数组,经过String构造函数将byte数组转换成String函数
注意:这种方式使用平台默认字符集学习
package com.bill.example; public class StringByteArrayExamples { public static void main(String[] args) { //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); } }
输出:编码
hello world
可能你已经了解 Base64 是一种将二进制数据编码的方式,正如UTF-8和UTF-16是将文本数据编码的方式同样,因此若是你须要将二进制数据编码为文本数据,那么Base64能够实现这样的需求加密
从Java 8 开始能够使用Base64这个类spa
import java.util.Base64;
public class StringByteArrayExamples { public static void main(String[] args) { //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) ); } }
输出:code
hello world
在byte[]和String互相转换的时候你应该注意输入数据的类型blog