如何将Java字符串转换为字节[]?
有没有办法将Java String
转换为 byte[]
(不是盒装的 Byte[]
)?
Is there any way to convert Java String
to a byte[]
(not the boxed Byte[]
)?
在尝试这个:
System.out.println(response.split("
")[1]);
System.out.println("******");
System.out.println(response.split("
")[1].getBytes().toString());
我得到了单独的输出.无法显示第一个输出,因为它是 gzip 字符串.
and I'm getting separate outputs. Unable to display 1st output as it is a gzip string.
<A Gzip String>
******
[B@38ee9f13
第二个是地址.有什么我做错了吗?我需要将 byte[]
中的结果提供给 gzip 解压缩器,如下所示.
The second is an address. Is there anything I'm doing wrong? I need the result in a byte[]
to feed it to gzip decompressor, which is as follows.
String decompressGZIP(byte[] gzip) throws IOException {
java.util.zip.Inflater inf = new java.util.zip.Inflater();
java.io.ByteArrayInputStream bytein = new java.io.ByteArrayInputStream(gzip);
java.util.zip.GZIPInputStream gzin = new java.util.zip.GZIPInputStream(bytein);
java.io.ByteArrayOutputStream byteout = new java.io.ByteArrayOutputStream();
int res = 0;
byte buf[] = new byte[1024];
while (res >= 0) {
res = gzin.read(buf, 0, buf.length);
if (res > 0) {
byteout.write(buf, 0, res);
}
}
byte uncompressed[] = byteout.toByteArray();
return (uncompressed.toString());
}
推荐答案
你的方法 decompressGZIP()
需要的对象是 byte[]
.
The object your method decompressGZIP()
needs is a byte[]
.
因此,您所提问题的基本技术答案是:
So the basic, technical answer to the question you have asked is:
byte[] b = string.getBytes();
byte[] b = string.getBytes(Charset.forName("UTF-8"));
byte[] b = string.getBytes(StandardCharsets.UTF_8); // Java 7+ only
<小时>
但是,您似乎遇到的问题是它的显示效果不是很好.调用 toString()
只会为您提供默认的 Object.toString()
,即类名 + 内存地址.在您的结果 [B@38ee9f13
中,[B
表示 byte[]
并且 38ee9f13
是内存地址,由 @
分隔.
However the problem you appear to be wrestling with is that this doesn't display very well. Calling toString()
will just give you the default Object.toString()
which is the class name + memory address. In your result [B@38ee9f13
, the [B
means byte[]
and 38ee9f13
is the memory address, separated by an @
.
出于显示目的,您可以使用:
For display purposes you can use:
Arrays.toString(bytes);
但这只会显示为逗号分隔的整数序列,这可能是也可能不是您想要的.
But this will just display as a sequence of comma-separated integers, which may or may not be what you want.
要从 byte[]
中获取可读的 String
,请使用:
To get a readable String
back from a byte[]
, use:
String string = new String(byte[] bytes, Charset charset);
<小时>
Charset
版本受到青睐的原因是,Java 中的所有 String
对象都在内部存储为 UTF-16.转换为 byte[]
时,您将获得该 String
的给定字形的不同字节细分,具体取决于所选的字符集.
The reason the Charset
version is favoured, is that all String
objects in Java are stored internally as UTF-16. When converting to a byte[]
you will get a different breakdown of bytes for the given glyphs of that String
, depending upon the chosen charset.
相关文章