Java: convert UTF8 String to byte array in another encoding

Pavel Vyazankin picture Pavel Vyazankin · Oct 26, 2010 · Viewed 22.3k times · Source

I have UTF8 encoded String, but I need to post parameters to Runtime process in cp1251. How can I decode String or byte array?

I need smth like:.bytesInCp1251 = encodeTo(stringInUtf8, "cp1251");


Thanks to all! This is my own solution:

OutputStreamWriter writer = new OutputStreamWriter(out, "cp1251");
writer.write(s);

Answer

Michael Borgwardt picture Michael Borgwardt · Oct 26, 2010

There is no such thing as an "UTF8 encoded String" in Java. Java Strings use UTF-16 internally, but should be seen as an abstraction without a specific encoding. If you have a String, it's already decoded. If you want to encode it, use string.getBytes(encoding). If you original data is UTF-8, you have to take that into account when you convert that data from bytes to String.