杰瑞科技汇

string 转byte java

在 Java 中,将 String 转换为 byte[](字节数组)有多种方法,具体取决于字符编码(如 UTF-8、GBK、ISO-8859-1 等),以下是几种常见的方法和示例代码:

string 转byte java-图1
(图片来源网络,侵删)

使用 `String.getBytes()(默认字符集)

String str = "Hello, 世界!";
byte[] bytes = str.getBytes(); // 使用 JVM 默认字符集(可能因环境而异)

注意:依赖默认字符集可能导致跨平台问题(不同系统默认编码不同),建议显式指定编码。


使用 `String.getBytes(Charset)(推荐)

显式指定字符集(如 UTF-8),避免环境差异导致的问题:

import java.nio.charset.StandardCharsets;
String str = "Hello, 世界!";
byte[] bytes = str.getBytes(StandardCharsets.UTF_8); // 推荐:明确指定编码

使用 `String.getBytes(String charsetName)

通过字符集名称(如 "UTF-8"、"GBK")转换:

String str = "Hello, 世界!";
try {
    byte[] utf8Bytes = str.getBytes("UTF-8");       // UTF-8 编码
    byte[] gbkBytes = str.getBytes("GBK");         // GBK 编码(中文常用)
    byte[] isoBytes = str.getBytes("ISO-8859-1");   // ISO-8859-1(仅支持 ASCII)
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

注意:需处理 UnsupportedEncodingException,但 Java 8+ 中常用字符集(如 UTF-8)通常不会抛出此异常。

string 转byte java-图2
(图片来源网络,侵删)

使用 `String.getBytes(StandardCharsets)(Java 7+)

Java 7 引入了 StandardCharsets 枚举,更安全且无需异常处理:

import java.nio.charset.StandardCharsets;
String str = "Hello, 世界!";
byte[] utf8Bytes = str.getBytes(StandardCharsets.UTF_8);
byte[] asciiBytes = str.getBytes(StandardCharsets.US_ASCII); // 仅支持 ASCII

使用 Charset.forName() 动态指定字符集

import java.nio.charset.Charset;
String str = "Hello, 世界!";
Charset charset = Charset.forName("UTF-8"); // 或 "GBK"、"ISO-8859-1" 等
byte[] bytes = str.getBytes(charset);

反向转换:byte[]String

byte[] bytes = "Hello, 世界!".getBytes(StandardCharsets.UTF_8);
String str = new String(bytes, StandardCharsets.UTF_8); // 使用相同编码

关键注意事项

  1. 字符集必须一致:编码和解码时使用相同的字符集(如 UTF-8),否则会出现乱码。
  2. 默认字符集不可靠:避免直接使用 getBytes(),显式指定编码更安全。
  3. 异常处理:如果使用字符串形式的字符集名称(如 "UTF-8"),需捕获 UnsupportedEncodingException(但 Java 7+ 中常用字符集通常不会抛出)。
  4. 性能StandardCharsetsCharset.forName() 的性能优于字符串形式的字符集名称。

完整示例

import java.nio.charset.StandardCharsets;
public class StringToByteExample {
    public static void main(String[] args) {
        String str = "Hello, 世界!";
        // String 转 byte[]
        byte[] utf8Bytes = str.getBytes(StandardCharsets.UTF_8);
        byte[] gbkBytes = str.getBytes(StandardCharsets.ISO_8859_1); // 仅 ASCII
        // byte[] 转 String
        String decodedStr = new String(utf8Bytes, StandardCharsets.UTF_8);
        System.out.println("Original: " + str);
        System.out.println("UTF-8 Bytes: " + new String(utf8Bytes, StandardCharsets.UTF_8));
        System.out.println("GBK Bytes (示例): " + new String(gbkBytes, StandardCharsets.ISO_8859_1));
        System.out.println("Decoded: " + decodedStr);
    }
}

常见字符集

字符集 说明 适用场景
UTF-8 支持所有 Unicode 字符 通用,推荐使用
GBK 支持中文字符 中文环境(如 Windows 中文版)
ISO-8859-1 仅支持 ASCII(0-127) 英文或二进制数据
US-ASCII 仅支持 ASCII(7 位) 英文

根据实际需求选择合适的字符集!

string 转byte java-图3
(图片来源网络,侵删)
分享:
扫描分享到社交APP
上一篇
下一篇