我有一个关于 Java 中字节的快速问题。

huangapple go评论70阅读模式
英文:

I Have A Fast Question Aboute Bytes in java

问题

Option 1

String inputString = "Hello World!";
byte[] byteArrray = inputString.getBytes();

Option 2

byte[] byteArrray = "Hello World!".getBytes();
英文:

Is Option 1 and 2 same do I need to create String inputString I making udpServer so I was wonder if it is okay do like option 2 or are they disadvantage that way.

Option 1

String inputString = "Hello World!";
byte[] byteArrray = inputString.getBytes();

Option 2

byte[] byteArrray = "Hello World!".getBytes();

答案1

得分: 3

以下是您要翻译的内容:

它们是相同的。也就是说,除了行号表之外,逐字节相同的字节码。但是,它们都非常可疑 - getBytes() 将使用 平台默认编码,而您真的不希望那样。在这个示例中,您的字符串全部都是ASCII,所以可能不太重要,但您的平台默认编码可能是UTF-16。

您需要指定使用的编码。通常使用的答案是UTF8。因此:

someString.getBytes(StandardCharsets.UTF8) 是您要寻找的内容,要从字节数组转换回字符串,使用 new String(byteArr, StandardCharsets.UTF8)

英文:

They are the same. As in, byte for byte same bytecode other than the linenumber table. But, they are both extremely suspect - getBytes() will use platform default encoding, and you really don't want that. It's somewhat unlikely to matter as your string in this example is all ASCII, but your platform default could conceivably be UTF-16.

You need to specify what encoding is used. The go-to answer tends to be UTF8. Thus:

someString.getBytes(StandardCharsets.UTF8) is what you're looking for, and to go from a byte array back to a string, new String(byteArr, StandardCharsets.UTF8).

huangapple
  • 本文由 发表于 2020年10月6日 23:01:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64228505.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定