如何在Java中初始化字节数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32662656/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:56:14  来源:igfitidea点击:

how to initialize byte array in Java?

javautf-8bytearray

提问by user1950349

I have a byte array like this: (this is not the actual byte array, I have modified it)

我有一个这样的字节数组:(这不是实际的字节数组,我已经修改了它)

[69, 121, 101, 45, 62, 118, 101, 114, 196, 195, 61, 101, 98]

I want to know how can I initialize this in Java so that I can convert this byte array to String? Below line doesn't work.

我想知道如何在 Java 中初始化它以便我可以将此字节数组转换为字符串?下面的行不起作用。

// this doesn't work
byte[] bytes = [69, 121, 101, 45, 62, 118, 101, 114, 196, 195, 61, 101, 98];

// now convert to string
String data = new String(bytes, StandardCharsets.UTF_8);

采纳答案by Suresh Atta

This should work

这应该工作

  byte[] bytes = {69, 121, 101, 45, 62, 118, 101, 114, (byte) 196, (byte) 195, 61, 101, 98};

Bytecan hold upto -128 to 127 only. Some of the values are exceeding the limit of a byte value. So you need to cast them to byte.

Byte最多只能容纳 -128 到 127。某些值超出了字节值的限制。所以你需要将它们转换为字节。