杰瑞科技汇

Java String转byte数组怎么转?

在 Java 中,将 String 转换为 byte 数组(byte[])是一个常见操作,但需要注意几个关键点,尤其是字符编码的选择,下面我将详细介绍不同的方法、注意事项以及完整的示例代码。


核心方法:String.getBytes()

Java 的 String 类提供了 getBytes() 方法,用于将字符串编码为 byte 数组,该方法有多个重载版本:

使用平台默认编码(不推荐)

String str = "你好,世界!";
byte[] bytes = str.getBytes(); // 使用 JVM 默认字符编码

⚠️ 注意:

  • 这种方法的行为依赖于运行环境的默认编码(Windows 可能是 GBK,Linux/macOS 可能是 UTF-8)。
  • 不推荐在生产代码中使用,因为不同环境可能导致不同的结果,引发乱码或数据不一致问题。

指定字符编码(推荐)

最安全的方式是显式指定字符编码(如 UTF-8GBK 等):

String str = "你好,世界!";
try {
    byte[] bytes = str.getBytes("UTF-8"); // 指明使用 UTF-8 编码
    // 或者使用 StandardCharsets.UTF-8(Java 7+ 推荐)
    // byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

优点:

  • 结果可预测,不受环境默认编码影响。
  • StandardCharsets(Java 7+)提供了预定义的常量,避免拼写错误和异常。

完整示例代码

示例 1:使用 UTF-8 编码

import java.nio.charset.StandardCharsets;
public class StringToByteExample {
    public static void main(String[] args) {
        String str = "Hello, 世界!";
        // 方法1:指定编码名称(需处理异常)
        try {
            byte[] bytes1 = str.getBytes("UTF-8");
            System.out.println("UTF-8 编码: " + java.util.Arrays.toString(bytes1));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 方法2:使用 StandardCharsets(Java 7+ 推荐)
        byte[] bytes2 = str.getBytes(StandardCharsets.UTF_8);
        System.out.println("StandardCharsets.UTF_8: " + java.util.Arrays.toString(bytes2));
        // 方法3:使用平台默认编码(不推荐)
        byte[] bytes3 = str.getBytes();
        System.out.println("默认编码: " + java.util.Arrays.toString(bytes3));
    }
}

输出示例(UTF-8 环境):

UTF-8 编码: [72, 101, 108, 108, 111, 44, 32, -28, -72, -83, -27, -101, -67, -28, -72, -83, 33]
StandardCharsets.UTF_8: [72, 101, 108, 108, 111, 44, 32, -28, -72, -83, -27, -101, -67, -28, -72, -83, 33]
默认编码: [72, 101, 108, 108, 111, 44, 32, -28, -72, -83, -27, -101, -67, -28, -72, -83, 33]

示例 2:使用 GBK 编码

String str = "你好";
byte[] gbkBytes = str.getBytes("GBK"); // GBK 编码
System.out.println("GBK 编码: " + java.util.Arrays.toString(gbkBytes));

输出示例:

GBK 编码: [-60, -29, -70, -61]

关键注意事项

  1. 字符编码的重要性

    • 如果编码和解码不一致,会导致乱码。
      String str = "你好";
      byte[] bytes = str.getBytes("GBK"); // 用 GBK 编码
      String decodedStr = new String(bytes, "UTF-8"); // 用 UTF-8 解码 → 乱码
      System.out.println(decodedStr); // 输出乱码字符
  2. 处理异常

    • getBytes(String charsetName) 可能抛出 UnsupportedEncodingException,但 StandardCharsets 中的常量不会抛出异常。
  3. 性能优化

    • 如果频繁转换,可以复用 Charset 对象:
      import java.nio.charset.Charset;
      Charset charset = Charset.forName("UTF-8");
      byte[] bytes = str.getBytes(charset);
  4. 字节数与字符数的区别

    • 一个 char 在 Java 中是 2 字节(UTF-16),但 byte[] 的长度取决于编码。
      • "A"(ASCII)→ 1 字节
      • "中"(UTF-8)→ 3 字节

反向操作:byte[]String

byte[] bytes = "你好".getBytes("UTF-8");
String str = new String(bytes, "UTF-8"); // 指明解码编码

方法 说明 推荐度
str.getBytes() 使用默认编码 ⭐(不推荐)
str.getBytes("UTF-8") 指定编码名称 ⭐⭐(需处理异常)
str.getBytes(StandardCharsets.UTF_8) 使用预定义编码常量 ⭐⭐⭐(推荐)

最佳实践:

  • 始终显式指定字符编码(如 UTF-8)。
  • 优先使用 StandardCharsets(Java 7+)。
  • 确保编码和解码的一致性。
分享:
扫描分享到社交APP
上一篇
下一篇