如何将 Java String 转换为 byte[]?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18571223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Java String into byte[]?
提问by Mkl Rjv
Is there any way to convert Java Stringto a byte[](notthe boxed Byte[])?
有什么方法可以将 Java 转换String为byte[](不是盒装的Byte[])?
In trying this:
在尝试这个:
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());
and I'm getting separate outputs. Unable to display 1st output as it is a gzip string.
我得到了单独的输出。无法显示第一个输出,因为它是一个 gzip 字符串。
<A Gzip String>
******
[B@38ee9f13
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.
第二个是地址。有什么我做错了吗?我需要a中的结果byte[]将其提供给gzip解压缩器,如下所示。
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());
}
采纳答案by Stewart
The object your method decompressGZIP()needs is a byte[].
您的方法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
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 [Bmeans byte[]and 38ee9f13is the memory address, separated by an @.
但是,您似乎遇到的问题是这不能很好地显示。调用toString()只会为您提供默认值Object.toString(),即类名 + 内存地址。在您的结果中[B@38ee9f13,[B手段byte[]和38ee9f13是内存地址,以@.
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 Stringback from a byte[], use:
要从 a 获得可读的String返回byte[],请使用:
String string = new String(byte[] bytes, Charset charset);
The reason the Charsetversion is favoured, is that all Stringobjects 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.
该Charset版本受到青睐的原因是StringJava 中的所有对象都在内部存储为 UTF-16。转换为 a 时,根据所选字符集,byte[]您将获得 that 的给定字形的不同字节细分String。
回答by Prabhakaran Ramaswamy
String example = "Convert Java String";
byte[] bytes = example.getBytes();
回答by Vimal Bera
You can use String.getBytes()which returns the byte[]array.
您可以使用String.getBytes()which 返回byte[]数组。
回答by Ankur Shanbhag
Try using String.getBytes(). It returns a byte[] representing string data. Example:
尝试使用 String.getBytes()。它返回一个 byte[] 表示字符串数据。例子:
String data = "sample data";
byte[] byteData = data.getBytes();
回答by Bhavesh
Simply:
简单地:
String abc="abcdefghight";
byte[] b = abc.getBytes();
回答by Lucas Hoepner
You might wanna try return new String(byteout.toByteArray(Charset.forName("UTF-8")))
你可能想试试 return new String(byteout.toByteArray(Charset.forName("UTF-8")))
回答by Yardack
It is not necessary to change java as a String parameter. You have to change the c code to receive a String without a pointer and in its code:
没有必要将 java 更改为 String 参数。您必须更改 c 代码以接收没有指针的字符串及其代码:
Bool DmgrGetVersion (String szVersion);
Char NewszVersion [200];
Strcpy (NewszVersion, szVersion.t_str ());
.t_str () applies to builder c ++ 2010
回答by Favnir Liorenth
I know I'm a little late tothe party but thisworks pretty neat (our professor gave it to us)
我知道我参加聚会有点晚了,但这很管用(我们的教授给了我们)
public static byte[] asBytes (String s) {
String tmp;
byte[] b = new byte[s.length() / 2];
int i;
for (i = 0; i < s.length() / 2; i++) {
tmp = s.substring(i * 2, i * 2 + 2);
b[i] = (byte)(Integer.parseInt(tmp, 16) & 0xff);
}
return b; //return bytes
}

