java?byte數(shù)組轉(zhuǎn)String的幾種常用方法
轉(zhuǎn)換方法概覽
在Java中,將byte數(shù)組轉(zhuǎn)換為String是常見的操作,尤其是在處理二進制數(shù)據(jù)和字符串表示之間轉(zhuǎn)換時。以下是Java中幾種常用的轉(zhuǎn)換方法。
String(byte[] bytes) 構(gòu)造器
這是最簡單的轉(zhuǎn)換方法,它使用平臺默認的字符集來解碼byte數(shù)組。
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) 構(gòu)造器
這個方法允許你指定byte數(shù)組的子序列進行轉(zhuǎn)換,通過offset
和length
參數(shù)。
byte[] bytes = new byte[]{72, 101, 108, 108, 111, 114, 108, 100}; // "HelloWorld" in ASCII String str = new String(bytes, 0, 5); // 只轉(zhuǎn)換前5個字符 System.out.println(str); // 輸出: Hello
String(byte[] bytes, Charset charset) 方法
使用Charset
參數(shù)可以指定特定的字符集進行解碼,這在處理非平臺默認字符集的數(shù)據(jù)時非常有用。
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) 方法
當需要指定字符集并且提供子序列的轉(zhuǎn)換時,可以使用這個方法。
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個字符開始轉(zhuǎn)換5個字符 System.out.println(str); // 輸出: World
String(byte[] bytes, String charsetName) 構(gòu)造器
這個構(gòu)造器允許你通過字符集名稱來解碼byte數(shù)組。
byte[] bytes = {72, 101, 108, 108, 111}; // "Hello" in ASCII String str = new String(bytes, "UTF-8"); System.out.println(str); // 輸出: Hello
附:通過String類將String轉(zhuǎn)換成byte[]或者byte[]轉(zhuǎn)換成String
用String.getBytes()方法將字符串轉(zhuǎn)換為byte數(shù)組,通過String構(gòu)造函數(shù)將byte數(shù)組轉(zhuǎn)換成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
總結(jié)
到此這篇關(guān)于java byte數(shù)組轉(zhuǎn)String的幾種常用方法的文章就介紹到這了,更多相關(guān)java byte數(shù)組轉(zhuǎn)String內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
淺談緩沖字符流 BufferedReader BufferedWriter用法
這篇文章主要介紹了緩沖字符流 BufferedReader BufferedWriter的用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07Spring 基于XML配置 bean管理 Bean-IOC的方法
這篇文章主要介紹了Spring 基于XML配置 bean管理 Bean-IOC的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2025-04-04spring boot 添加admin監(jiān)控的方法
這篇文章主要介紹了spring boot 添加admin監(jiān)控的相關(guān)知識,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2018-02-02Springboot Cache @CacheEvict 無法模糊刪除的解決方案
這篇文章主要介紹了Springboot Cache @CacheEvict 無法模糊刪除的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12