1

I have array of bytes that should be converted to string. That array consists of Windows-1257 encoded text. What is the best way of converting this array to string? Later I will need to convert string to ISO-8859-13 byte array, but I know how to make this part of job.

I tried like this:

String result = new String(currentByteArray, "ISO-8859-13");

But of course got garbage in local character places.

vico
  • 17,051
  • 45
  • 159
  • 315
  • http://stackoverflow.com/questions/655891/converting-utf-8-to-iso-8859-1-in-java-how-to-keep-it-as-single-byte – isnot2bad Sep 28 '13 at 10:49
  • There's no such thing as "ISO-8859-13 string" - you can convert to `String`, then convert to binary data using ISO-8859-13 though - is that what you're trying to do? – Jon Skeet Sep 28 '13 at 10:53
  • Actually I need to make string from Windows-1257 encoded byte array. I need to use this string in my program and later i will need this string to convert to ISO-8859-13 byte array. Question is how to upload Windows-1257 byte array to string? – vico Sep 28 '13 at 11:01
  • You tell Java to decode the byte array from ISO-8859-13, but according to your question, it contains Windows-1257. Hence you get garbage. – Ingo Sep 28 '13 at 11:21

1 Answers1

4
String unicodeString = new String(currentByteArray, "Windows-1257");
byte[] result = unicodeString.getBytes("ISO-8859-13");

or

PrintWriter out = new PrintWriter(file, "ISO-8859-13");

Java is very simple: String/Reader&Writer is Unicode text capable to contain all characters. And binary byte[]s/InputStream&OutputStream is for binary data.

Hence the String constructor for bytes needs the original encoding of those bytes, and getting bytes needs the encoding where those bytes should be in.

Be aware that there are overloaded versions with one parameter, without encoding. That uses the platform encoding; not-portable.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138