转换方法概览
在Java中,将byte数组转换为String是常见的操作,尤其是在处理二进制数据和字符串表示之间转换时。以下是Java中几种常用的转换方法。
String(byte[] bytes) 构造器
这是最简单的转换方法,它使用平台默认的字符集来解码byte数组。
1 2 3 | 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
参数。
1 2 3 | 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
参数可以指定特定的字符集进行解码,这在处理非平台默认字符集的数据时非常有用。
1 2 3 | 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) 方法
当需要指定字符集并且提供子序列的转换时,可以使用这个方法。
1 2 3 | 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数组。
1 2 3 | 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
注意:这种方式使用平台默认字符集
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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); } } |
输出:
1 | hello world |
总结
到此这篇关于java byte数组转String的几种常用方法的文章就介绍到这了,更多相关java byte数组转String内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!