使用Windows-1252读写文件

罗伯特

我正在尝试将包含一些德语字符的文件写入磁盘,并使用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);
}
灵魂大师

您的写入方法错误。您正在使用写入器来写入字节应该使用作家来写字符或字符串。

您已经使用以下代码将字符串编码为字节

byte[] bytes = html.getBytes(charset);

这些字节可以简单地写入输出流:

IOUtils.write(bytes, outputStream);

这样就不需要编写器(删除它),您现在将获得正确的输出。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章