If you have a String
, you can do that:
String s = "test";
try {
s.getBytes("UTF-8");
} catch(UnsupportedEncodingException uee) {
uee.printStackTrace();
}
If you have a 'broken' String
, you did something wrong, converting a String
to a String
in another encoding is defenetely not the way to go! You can convert a String
to a byte[]
and vice-versa (given an encoding). In Java String
s are AFAIK encoded with UTF-16
but that's an implementation detail.
Say you have a InputStream
, you can read in a byte[]
and then convert that to a String
using
byte[] bs = ...;
String s;
try {
s = new String(bs, encoding);
} catch(UnsupportedEncodingException uee) {
uee.printStackTrace();
}
or even better (thanks to erickson) use InputStreamReader
like that:
InputStreamReader isr;
try {
isr = new InputStreamReader(inputStream, encoding);
} catch(UnsupportedEncodingException uee) {
uee.printStackTrace();
}