jimmy
jimmy

Reputation: 8381

converting a String to UTF8 format

I java code, I am having a string name = "örebro"; // its a swedish character.

But when I use this name in web application. I print some special character at 'Ö' character.

Is there anyway I can use the same character as it is in "örebro".

I did some thing like this but does not worked.

String name = "örebro";
byte[] utf8s = name .getBytes("UTF-8"); 
name = new String(utf8s, "UTF-8");

But the name at the end prints the same, something like this. �rebo

Please guide me

Upvotes: 2

Views: 7092

Answers (4)

Xavier Combelle
Xavier Combelle

Reputation: 11195

If the page used to generate the output is jsp it's useful to precise

<%@ page contentType="text/html; charset=utf-8" %>

Upvotes: 1

D&#233;j&#224; vu
D&#233;j&#224; vu

Reputation: 28830

It is likely the browser that reads the page does not know the encoding.

  • send the header (before any other output) something in Java like
    ServletResponse resource; (...)
    resource.setContentType ("text/html;charset=utf-8");

  • in your html page, mention the encoding by sending (printing)
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Upvotes: 1

Michael Borgwardt
Michael Borgwardt

Reputation: 346240

The Java code you've provided is pointless, it will do nothing. Java Strings are already perfectly capable of encoding any character (though you have to be careful with literals in the source code, as they depend on the encoding the compiler uses, which is platform-dependant).

Most likely your problem is that your webpage does not declare the encoding correctly in the HTTP header or the HTML meta tags.

Upvotes: 4

SLaks
SLaks

Reputation: 887195

You need to set the encoding of your output to UTF8.

Upvotes: 3

Related Questions