java?byte數(shù)組轉String的幾種常用方法
轉換方法概覽
在Java中,將byte數(shù)組轉換為String是常見的操作,尤其是在處理二進制數(shù)據(jù)和字符串表示之間轉換時。以下是Java中幾種常用的轉換方法。
String(byte[] bytes) 構造器
這是最簡單的轉換方法,它使用平臺默認的字符集來解碼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) 構造器
這個方法允許你指定byte數(shù)組的子序列進行轉換,通過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); // 只轉換前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) 方法
當需要指定字符集并且提供子序列的轉換時,可以使用這個方法。
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數(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轉換成byte[]或者byte[]轉換成String
用String.getBytes()方法將字符串轉換為byte數(shù)組,通過String構造函數(shù)將byte數(shù)組轉換成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數(shù)組轉String的幾種常用方法的文章就介紹到這了,更多相關java byte數(shù)組轉String內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Springboot-admin整合Quartz實現(xiàn)動態(tài)管理定時任務的過程詳解
Quartz是一款Java編寫的開源任務調(diào)度框架,同時它也是Spring默認的任務調(diào)度框架,它的作用其實類似于Timer定時器以及ScheduledExecutorService調(diào)度線程池,這篇文章主要介紹了Springboot-admin整合Quartz實現(xiàn)動態(tài)管理定時任務,需要的朋友可以參考下2023-04-04
解決Error:(5, 28) java: 程序包org.apache.ibatis.io
這篇文章主要介紹了解決Error:(5, 28) java: 程序包org.apache.ibatis.io不存在問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05
Java Spring MVC 上傳下載文件配置及controller方法詳解
這篇文章主要介紹了Java Spring MVC 上傳下載文件配置及controller方法詳解,本文介紹的非常詳細,具有參考借鑒價值,需要的朋友可以參考下2016-09-09
java實例方法被覆蓋,靜態(tài)方法被隱藏Explain(詳解)
下面小編就為大家?guī)硪黄猨ava實例方法被覆蓋,靜態(tài)方法被隱藏Explain(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-05-05
Spring Boot的測試類中使用 @Transactional 注解
本文主要介紹了Spring Boot的測試類中使用 @Transactional 注解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2026-05-05

