java - 如何在 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[] 中?
解决方案
为什么要这样做byte[] Source2 = a.toString().getBytes();
?
这似乎是双重转换;您将 a 转换byte[]
为string
tobyte[].
byte[]
a到字符串的真正转换是new String(byte[])
希望您使用相同的字符集。
Source2
应该是一个精确的副本,a
因此你应该这样做byte[] Source2 = a;
推荐阅读
- python - 从分布中计算元素的可能性
- javascript - 如何在 bootstrapvue 中创建收藏夹?
- angular - 我们如何选择打开和关闭的 2 个数据列中的最小值,使用这些点来定义我的 y 轴?
- powershell - Connect-PowerBiServiceAccount 无法与服务主体连接
- qt - 设置填充时如何避免绑定循环?
- linux - 使用 bash 脚本根据文件夹名称移动文件夹
- json - MongoDB - 关系化包含数组的 JSON
- javascript - Wave 可访问性检查中的空按钮错误
- modelica - 使用“外部”参数重新声明模型
- java - org.apache.tomcat-embed-core 的 java 模块是什么?