首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用windows-1252读写文件

用windows-1252读写文件
EN

Stack Overflow用户
提问于 2015-04-23 08:54:07
回答 2查看 2.2K关注 0票数 3

我正在尝试将一个包含一些德语字符的文件写入磁盘,并使用Windows-1252编码读取它。我不明白为什么,但我的输出是这样的:

代码语言:javascript
复制
<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来运行它。

代码语言:javascript
复制
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);
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-04-23 09:22:48

你的写作方法是错误的。您正在使用编写器来编写字节。作者应用于书写字符或字符串。

您已经用行将字符串编码为字节。

代码语言:javascript
复制
byte[] bytes = html.getBytes(charset);

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

代码语言:javascript
复制
IOUtils.write(bytes, outputStream);

这使得编写器没有必要(删除它),您现在将得到正确的输出。

票数 1
EN

Stack Overflow用户

发布于 2015-04-23 10:15:36

首先,确保编译器和编辑器使用相同的编码。可以对此进行检查,尝试(丑陋的) \uXXXX转义:

代码语言:javascript
复制
während
w\u00E4hrend

然后

代码语言:javascript
复制
    "<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 )允许播放编码。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29818400

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档