How to encode a string in UTF-8 from a ResultSet e

2019-02-25 15:52发布

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.

3条回答
我想做一个坏孩纸
2楼-- · 2019-02-25 16:12

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();
    }
查看更多
趁早两清
3楼-- · 2019-02-25 16:22
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

查看更多
▲ chillily
4楼-- · 2019-02-25 16:24

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"));
查看更多
登录 后发表回答