Java: convert UTF8 String to byte array in different encoding

I have a UTF8 encoded string, but I need to send parameters to the execution process in cp1251. How can I decode a String or byte array?

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


Thanks everyone! This is my own solution:

 OutputStreamWriter writer = new OutputStreamWriter(out, "cp1251"); writer.write(s); 
+4
source share
4 answers

There is no such thing as a โ€œUTF8 encoded stringโ€ in Java . Java strings use UTF-16 internally, but should be considered an abstraction without a specific encoding. If you have a String, it is already decoded. If you want to encode it, use string.getBytes(encoding) . If the source data is UTF-8, you should consider this when converting this data from bytes to String.

+9
source
 byte[] bytesInCp1251 = stringInUtf8.getBytes("cp1251"); 
+5
source

This is the solution!

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

Why not do something like this (assuming stringInUtf8 is a UTF-8 string)?

 String cp1251Str = new String(stringInUtf8.getBytes("UTF-8"), "cp1251"); 
0
source

All Articles