我正在尝试将一个包含一些德语字符的文件写入磁盘,并使用Windows-1252编码读取它。我不明白为什么,但我的输出是这样的:
<title>W�hrend und im Anschluss an die Exkursion stehen Ihnen die Ansprechpartner f�r O-T�ne</title>
<p>Die Themen im �berblick</p>有什么想法吗?这是我的密码。你需要spring和commons来运行它。
private static void write(String fileName, Charset charset) throws IOException {
String html = "<html xmlns=\"http://www.w3.org/1999/xhtml\">" +
"<head>" +
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=windows-1252\">" +
"<title>Während und im Anschluss an die Exkursion stehen Ihnen die Ansprechpartner für O-Töne</title>" +
"</head>" +
"<body>" +
"<p>Die Themen im Überblick</p>" +
"</body>" +
"</html>";
byte[] bytes = html.getBytes(charset);
FileOutputStream outputStream = new FileOutputStream(fileName);
OutputStreamWriter writer = new OutputStreamWriter(outputStream, charset);
IOUtils.write(bytes, writer);
writer.close();
outputStream.close();
}
private static void read(String file, Charset windowsCharset) throws IOException {
ClassPathResource pathResource = new ClassPathResource(file);
String string = IOUtils.toString(pathResource.getInputStream(), windowsCharset);
System.out.println(string);
}
public static void main(String[] args) throws IOException {
Charset windowsCharset = Charset.forName("windows-1252");
String file = "test.txt";
write(file, windowsCharset);
read(file, windowsCharset);
}发布于 2015-04-23 09:22:48
你的写作方法是错误的。您正在使用编写器来编写字节。作者应用于书写字符或字符串。
您已经用行将字符串编码为字节。
byte[] bytes = html.getBytes(charset);可以简单地将这些字节写入输出流:
IOUtils.write(bytes, outputStream);这使得编写器没有必要(删除它),您现在将得到正确的输出。
发布于 2015-04-23 10:15:36
首先,确保编译器和编辑器使用相同的编码。可以对此进行检查,尝试(丑陋的) \uXXXX转义:
während
w\u00E4hrend然后
"<meta http-equiv='Content-Type' content='text/html; charset="
+ charset.name() + "' />" +
byte[] bytes = html.getBytes(charset);
Files.write(Paths.get(fileName), bytes);啊,检查一下文件是否也在Windows1252中。程序员的编辑器(如NotePad++或JEdit )允许播放编码。
https://stackoverflow.com/questions/29818400
复制相似问题