How to convert a Java String to an ASCII byte array?
If you are a guava user there is a handy Charsets
class:
String s = "Hello, world!";byte[] b = s.getBytes(Charsets.US_ASCII);
Apart from not hard-coding arbitrary charset name in your source code it has a much bigger advantage: Charsets.US_ASCII
is of Charset
type (not String
) so you avoid checked UnsupportedEncodingException
thrown only from String.getBytes(String)
, but not from String.getBytes(Charset)
.
In Java 7 there is equivalent StandardCharsets
class.
There is only one character wrong in the code you tried:
Charset characterSet = Charset.forName("US-ASCII");String string = "Wazzup";byte[] bytes = String.getBytes(characterSet); ^
Notice the upper case "String". This tries to invoke a static method on the string class, which does not exist. Instead you need to invoke the method on your string instance:
byte[] bytes = string.getBytes(characterSet);