Convert string from UTF-8 to ISO 8859-1 in Java

I want to encode UTF-8 string to ISO 8859 string in Java

I have it:

String title = new String(item.getTitle().getText().getBytes("ISO-8859-1"));

      

But it does not work, Sørensen exit for example

+2


a source to share


2 answers


In Java, there is no such thing as "UTF-8 string" ... there are only strings that are always in Unicode. (They are always always UTF-16.)

You can have a byte array that is an ISO-8859-1 encoded form of a string (or UTF-8 or whatever), but it doesn't make sense to have an encoded string.



If you've read a string with the wrong encoding somewhere, the correct thing to do is fix the code that reads the string, instead of later trying to decode / encode the data from the string form.

If you could provide more information about the problem, we can perhaps provide some more useful advice.

+7


a source


This problem should not be solved this way. Strings in Java are always in the same encoding (UTF-16), you basically just changed the content. You need to set the encoding at the destination of this string. If it's stdout you need to set its encoding. If it's a file, you need to set its Writer

encoding. If it is an HTML page, you need to set the encoding of the response. If it is a database, you need to set the encoding to DB / table / connection. Etcetera.

Update : as per the comments:

A string from an RSS feed that is in UTF-8 and I want to show in an HTML page that uses ISO 8859 encoding

You will need to update the HTML page encoding from the vintage ISO 8859 encoding to the modern UTF-8 encoding based on world domination.

Update 2: as per the comments:



Firefox shows it in the correct default encoding (utf-8), but Internet Explorer for example doesn't

Then the text is really beautiful. You don't need to mass the string to a different encoding. Symptoms indicate that there is no character encoding information in the response headers. Firefox does have a pretty smart encoding detector, while IE will use the platform's default encoding when the encoding is unknown. But IE will also fail if HTML is (radically) mangled in doctype and head.

So either the HTML response is not syntactically valid, or the response content type was not set correctly. Assuming your site is validating and that you are using a JSP / Servlet (after evaluating your post history here), you basically need to add the following lines at the top of your JSP:

<%@ page pageEncoding="UTF-8" %>

      

It's all. It will automatically set both the encoding of the response (so that the server knows which encoding will be used to write characters to the response byte stream) and the encoding in the response header Content-Type

(so that the client knows which encoding is used to read / display those characters from the response byte stream). For more information, you can find this article .

+4


a source







All Articles