如何将Java String转换为byte []? [英] How to convert Java String into byte[]?
问题描述
有没有办法将Java String
转换为 byte []
( not 盒装的 Byte []
)?
Is there any way to convert Java String
to a byte[]
(not the boxed Byte[]
)?
尝试这个:
System.out.println(response.split("\r\n\r\n")[1]);
System.out.println("******");
System.out.println(response.split("\r\n\r\n")[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 decompressor,如下所示。
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 []
。
所以您提出的问题的基本技术答案是:
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.
从字节[]中获取可读的
,使用:字符串
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.
这篇关于如何将Java String转换为byte []?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!