开发者

Does Java have a function to convert a string to a byte array?

开发者 https://www.devze.com 2022-12-13 23:39 出处:网络
Is there any function in Java that converts a string to a byte array?开发者_运维百科Yes: String.getBytes. You really, really want to specify the character encoding when you do so though - using the pl

Is there any function in Java that converts a string to a byte array?开发者_运维百科


Yes: String.getBytes. You really, really want to specify the character encoding when you do so though - using the platform default encoding is almost always the wrong thing to do.

Ideally, it's best to specify the encoding via a Charset - that way you don't need to worry about the UnsupportedEncodingException which can be thrown by the overload of getBytes which just takes a String with the character encoding name as an argument.

EDIT: Based on your comment, it looks like you want to parse a hex string into a byte array. (It would have been useful to say so in your question.) String.getBytes is inappropriate for this - I don't believe there's anything which does this in the standard libraries, but the Apache Commons Codec library makes it pretty easy:

byte[] data = Hex.decodeHex(text.toCharArray());


String.getBytes()?


Have you tried?

"whatever".getBytes()
0

精彩评论

暂无评论...
验证码 换一张
取 消