首页 > 解决方案 > 如何在 JAVA 中将字符串变量转换回字节 []

问题描述

我有以下代码来压缩和解压缩字符串:

public static void main(String[] args) {
    // TODO code application logic here
    String Source = "hello world";
    byte[] a = ZIP(Source);
    System.out.format("answer:");
    System.out.format(a.toString());
    System.out.format("\n");


    byte[] Source2 = a.toString().getBytes();

    System.out.println("\nsource 2:" + Source2.toString() + "\n");

    String b = unZIP(Source2);
    System.out.println("\nunzip answer:");
    System.out.format(b);
    System.out.format("\n");


}

  public static byte[] ZIP(String source) {
      ByteArrayOutputStream bos= new ByteArrayOutputStream(source.length()* 4);

      try {
          GZIPOutputStream outZip= new GZIPOutputStream(bos);
          outZip.write(source.getBytes());
          outZip.flush();
          outZip.close();
      } catch (Exception Ex) {
      }
      return bos.toByteArray();
  }

public static String unZIP(byte[] Source) {
    ByteArrayInputStream bins= new ByteArrayInputStream(Source);
    byte[] buf= new byte[2048];
    StringBuffer rString= new StringBuffer("");
    int len;

    try {
        GZIPInputStream zipit= new GZIPInputStream(bins);
        while ((len = zipit.read(buf)) > 0) {
             rString.append(new String(buf).substring(0, len));
        }
        return rString.toString();
    } catch (Exception Ex) {
       return "";
    }
}

当 "Hello World" 被压缩后,它会变成 [B@7bdecdec in byte[] 并转换成 String 并显示在屏幕上。但是,如果我尝试使用以下代码将字符串转换回 byte[]:

 byte[] Source2 = a.toString().getBytes();

变量 a 的值将变为 [B@60a1807c 而不是 [B@7bdecdec 。有谁知道如何在 JAVA 中将字符串(字节的值但已转换为字符串)转换回 byte[] 中?

标签: java

解决方案


为什么要这样做byte[] Source2 = a.toString().getBytes();

这似乎是双重转换;您将 a 转换byte[]stringtobyte[].

byte[]a到字符串的真正转换是new String(byte[])希望您使用相同的字符集。

Source2应该是一个精确的副本,a因此你应该这样做byte[] Source2 = a;


推荐阅读