我正在生成带有这些数据的 html 文件(存储在 postgres 中):
html 文件生成为 UTF-8,但字符串看起来像是出现在数据库中。
如何使文本正确显示?喜欢:Ú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 值。我只会指出它是如何工作的,您必须自己完成正确的实现。
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/