java从postgres转换为utf-8

标签 java encoding utf-8

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

my data in postgres

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

generated html file

如何使文本正确显示?喜欢:Últiles de Escritorio

注意。我无法更改 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")

最佳答案

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

因为你不能改变你的数据库设置,这不是那么容易处理,首先你必须知道文本将以哪种格式保存在你的数据库中,参见here .

你应该熟悉 UTF16,请参阅 herehere .

现在,在您熟悉要使用的编解码器之后,您必须为从数据库中获取的每个字符创建正确的 utf16 值。我只会指出它是如何工作的,您必须自己完成正确的实现。

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

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

真诚的

关于java从postgres转换为utf-8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6575428/

相关文章:

java - 当用户按没有值的回车键时,如何在java中显示int的空消息

android - 通过蓝牙从 Android 在 Zebra 打印机上打印数据

PHP 使用 Shift_JIS 转换编码

perl - 基准 utf8 文件读取 - 差异说明

mysql - 无法通过utf8编码在mysql数据库中插入中文(Warning 1336 incorrect string value)

java - 显示我的数据库中的名称时遇到问题

java.lang.IllegalStateException : Parent was not null, 但此组件不相关

java - 我有一个打开 GUI 的按钮,如何设置 GUI 在屏幕上显示的位置?

PHP内部编码

ruby - Microsoft Word 符号的编码问题 [UTF-8 到 ISO-5589-1]