Java: convert UTF8 String to byte array in another encoding

cp1251, encoding, java

Solution

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.

Problem

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); ```

Original source