英文:
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)
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论