If you have a String , you can do this:
String s = "test"; try { s.getBytes("UTF-8"); } catch(UnsupportedEncodingException uee) { uee.printStackTrace(); }
If you have a “broken” String , you did something wrong, converting String to String to another encoding does not meet the requirements! You can convert String to byte[] and vice versa (given the encoding). Java String contains AFAIK encoded using UTF-16 , but these are implementation details.
Say you have an InputStream , you can read in byte[] and then convert it to String using
byte[] bs = ...; String s; try { s = new String(bs, encoding); } catch(UnsupportedEncodingException uee) { uee.printStackTrace(); }
or even better (thanks erickson) use InputStreamReader as follows:
InputStreamReader isr; try { isr = new InputStreamReader(inputStream, encoding); } catch(UnsupportedEncodingException uee) { uee.printStackTrace(); }
Johannes Weiss Mar 16 '09 at 21:30 2009-03-16 21:30
source share