java?byte數組轉String的幾種常用方法
轉換方法概覽
在Java中,將byte數組轉換為String是常見的操作,尤其是在處理二進制數據和字符串表示之間轉換時。以下是Java中幾種常用的轉換方法。
String(byte[] bytes) 構造器
這是最簡單的轉換方法,它使用平臺默認的字符集來解碼byte數組。
byte[] bytes = {72, 101, 108, 108, 111}; // "Hello" in ASCII String str = new String(bytes); System.out.println(str); // 輸出: Hello
String(byte[] bytes, int offset, int length) 構造器
這個方法允許你指定byte數組的子序列進行轉換,通過offset
和length
參數。
byte[] bytes = new byte[]{72, 101, 108, 108, 111, 114, 108, 100}; // "HelloWorld" in ASCII String str = new String(bytes, 0, 5); // 只轉換前5個字符 System.out.println(str); // 輸出: Hello
String(byte[] bytes, Charset charset) 方法
使用Charset
參數可以指定特定的字符集進行解碼,這在處理非平臺默認字符集的數據時非常有用。
byte[] bytes = {72, 101, 108, 108, 111}; // "Hello" in ASCII String str = new String(bytes, StandardCharsets.UTF_8); System.out.println(str); // 輸出: Hello
String(byte[] bytes, int offset, int length, String charsetName) 方法
當需要指定字符集并且提供子序列的轉換時,可以使用這個方法。
byte[] bytes = new byte[]{72, 101, 108, 108, 111, 114, 108, 100}; // "HelloWorld" in ASCII String str = new String(bytes, 6, 5, "US-ASCII"); // 從第6個字符開始轉換5個字符 System.out.println(str); // 輸出: World
String(byte[] bytes, String charsetName) 構造器
這個構造器允許你通過字符集名稱來解碼byte數組。
byte[] bytes = {72, 101, 108, 108, 111}; // "Hello" in ASCII String str = new String(bytes, "UTF-8"); System.out.println(str); // 輸出: Hello
附:通過String類將String轉換成byte[]或者byte[]轉換成String
用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
總結
到此這篇關于java byte數組轉String的幾種常用方法的文章就介紹到這了,更多相關java byte數組轉String內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java HashSet(散列集),HashMap(散列映射)的簡單介紹
這篇文章主要介紹了Java HashSet(散列集),HashMap(散列映射)的簡單介紹,幫助大家更好的理解和學習Java集合框架的相關知識,感興趣的朋友可以了解下2021-01-01