java从postgres转换为utf-8

时间:2011-07-04 19:35:49

标签: java encoding utf-8

我正在生成这些数据的html文件(存储在postgres中):

my data in postgres

html文件生成为UTF-8,但字符串看起来像是出现在数据库中。

generated html file

如何才能使文字正确显示?喜欢: ÚltilesdeEscritorio

请注意。我无法改变postgres配置,我使用的是Java 1.6,Postgres 8.4,JDBC

更新:

我使用此代码创建html文件:

public static void stringToFile (String file_name, String file_content) throws IOException {
    OutputStream out = new FileOutputStream(file_name);
    OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");

    try {
        try {
            writer.write(file_content);
        } finally {
            writer.close();
        }
    } finally {
        out.close();
    }
}

我用它像:

StringBuilder html_content = new StringBuilder();

ResultSet result_set = statement.executeQuery(sql_query);

while (result_set.next()) {
    html_content.append(String.format('<li>%s</li>', result_set.getString(1)));
}

Utils.stringToFile('thehtmlfile.html', html_content.toString());

更新:[已解决] 这对我有用:

new String(str.getBytes("ISO-8859-1"), "UTF-8")

1 个答案:

答案 0 :(得分:0)

我希望您确定在将字符串添加到数据库之前不会发生错误。

由于您无法更改数据库设置,因此处理起来并不容易,首先您必须知道文本将以哪种格式保存在数据库中,请参阅here

您应该熟悉UTF16,请参阅herehere

现在,在您熟悉要使用的编解码器之后,必须为从db获得的每个字符创建正确的utf16值。我只想指出它是如何工作的,你必须自己做正确的实现。

public char createUTF16char( char first, char second ) {
  char res = first;
  res = res << 8;
  res = res & (0x0F & second);
  return res;
}

此代码应该将每个char(第一个和第二个)的最后8位组合成一个新的char。 也许这是您需要的操作,但这取决于服务器上使用的编码。

此致