我正在尝试将包含一些德语字符的文件写入磁盘并使用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-core 和 commons-io 来运行它。
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);
}