views:

47

answers:

4

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);
A: 

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

String cp1251Str = new String(stringInUtf8.getBytes("UTF-8"), "cp1251");
The Elite Gentleman
stringInUtf8 was in UTF8, then converts to byte array in UTF8, then it reads like cp1251.. but it was in UTF8!
dart
@dart, sorry...edited
The Elite Gentleman
Still completely wrong. Your code will do nothing exceopt corrupt the data.
Michael Borgwardt
@Michael Borgwardt, true, but that is expected (because of the conversion between charset)
The Elite Gentleman
+2  A: 
byte[] bytesInCp1251 = stringInUtf8.getBytes("cp1251");
William
see comment above
dart
+6  A: 

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.

Michael Borgwardt
sorry, String was UTF8 encoded.
dart
It works! Thank you)
dart
A: 

This is solution!

OutputStreamWriter writer = new OutputStreamWriter(out, "cp1251");
writer.write(s);
dart
You should update your own answer with the solution instead of it being hidden here.
Shervin