5

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);
Pavel Vyazankin
  • 1,470
  • 6
  • 18
  • 27
  • possible duplicate of [How to parse a string that is in a different encoding from java](http://stackoverflow.com/questions/4016671/how-to-parse-a-string-that-is-in-a-different-encoding-from-java) – Bozho Oct 26 '10 at 09:21
  • There are no answer for my question there. I need to _change_ encoding. – Pavel Vyazankin Oct 26 '10 at 09:30
  • possible duplicate of [Encoding conversion in java](http://stackoverflow.com/questions/229015/encoding-conversion-in-java) – kamaci Aug 26 '12 at 14:25

3 Answers3

9

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
  • 342,105
  • 78
  • 482
  • 720
5
byte[] bytesInCp1251 = stringInUtf8.getBytes("cp1251");
William
  • 13,332
  • 13
  • 60
  • 73
1

This is solution!

OutputStreamWriter writer = new OutputStreamWriter(out, "cp1251");
writer.write(s);
Shervin Asgari
  • 23,901
  • 30
  • 103
  • 143
Pavel Vyazankin
  • 1,470
  • 6
  • 18
  • 27