經過用例學習Java中的byte數組和String互相轉換,這種轉換可能在不少狀況須要,好比IO操做,生成加密hash碼等等。html
除非以爲必要,不然不要將它們互相轉換,他們分別表明了不一樣的數據,專門服務於不一樣的目的,一般String表明文本字符串,byte數組針對二進制數據java
用String.getBytes()方法將字符串轉換爲byte數組,經過String構造函數將byte數組轉換成String數組
注意:這種方式使用平臺默認字符集app
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這個類編碼
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) ); } }
輸出:加密
hello world
在byte[]和String互相轉換的時候你應該注意輸入數據的類型spa
若有問題請在評論留言code
Happy Learning !!
本文轉自:https://www.cnblogs.com/keeplearnning/p/7003415.html