Wellington Souza
Wellington Souza

Reputation: 2358

How to encode a string in UTF-8 from a ResultSet encoded in latin1

I'm writing an application (uses UTF-8) that need read/write to a second database of an external application (uses ISO-8859-1).

try {
    // data in latin1
    String s = rs.getString("sAddrNameF");
    System.out.println(s); // shows "Adresse d'exp�dition"
    byte[] data = s.getBytes();
    String value = new String(data, "UTF-8");
    System.out.println("data in UTF8: " + value);
    // The expected result should be "Adresse d'expédition"
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
}

This code is not working, I also still need do the opposite conversion (writing on the database). If anybody know an elegant solution to dealing with different encoding in the same application please let me know, I appreciate it.

Upvotes: 3

Views: 12929

Answers (4)

Noureddine Ad
Noureddine Ad

Reputation: 29

String value = new String(data,"ISO-8859-1");

Upvotes: 0

Balkrushna Patil
Balkrushna Patil

Reputation: 466

We need to mension string as StandardCharsets.UTF_8

try {
        // data in latin1
        String s = rs.getString("sAddrNameF");
        System.out.println(s); // shows "Adresse d'exp�dition"
        byte[] data = rs.getBytes("sAddrNameF");
        String value = new String(data, StandardCharsets.UTF_8);
        System.out.println("data in UTF8: " + value);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

Upvotes: -1

Kayaman
Kayaman

Reputation: 73558

String s = rs.getString("sAddrNameF");
System.out.println(s); // shows "Adresse d'exp�dition"

This means that the string is either already corrupted in the database, or you're connecting to the database with the wrong encoding (such as passing characterEncoding=utf8 with MySQL).

There's no such a thing as converting String from one encoding to another. Once you have a String it's always UTF-16.

If it's just a configuration problem, you don't need to worry. The rs.getString() will return proper Strings and PreparedStatement.setString() will make sure Strings are properly saved in the database.

What you should know about Unicode

Upvotes: 6

Wladimir Schmidt
Wladimir Schmidt

Reputation: 274

The function getBytes takes also a Charset or just string with the desired encoding.

byte[] data = s.getBytes("UTF-8");
// or
byte[] data = s.getBytes(Charset.forName("UTF-8"));

Upvotes: -2

Related Questions