【问题标题】:Reading and writing file in ISO-8859-1 encoding?以 ISO-8859-1 编码读写文件?
【发布时间】:2020-08-11 17:25:00
【问题描述】:

我有以 ISO-8859-1 编码的文件。我正在尝试将其作为单个字符串读入,对其进行一些正则表达式替换,然后以相同的编码将其写回。

但是,我得到的结果文件似乎总是 UTF-8(至少根据 Notepad++),会损坏一些字符。

谁能看到我在这里做错了什么?

private static void editFile(File source, File target) {

    // Source and target encoding
    Charset iso88591charset = Charset.forName("ISO-8859-1");

    // Read the file as a single string
    String fileContent = null;

    try (Scanner scanner = new Scanner(source, iso88591charset)) {
    
        fileContent = scanner.useDelimiter("\\Z").next();
                
    } catch (IOException exception) {
        LOGGER.error("Could not read input file as a single String.", exception);
        return;
    }

    // Do some regex substitutions on the fileContent string
    String newContent = regex(fileContent);

    // Write the file back out in target encoding
    try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target), iso88591charset))) {
    
        writer.write(newContent);
        
    } catch (Exception exception) {
        LOGGER.error("Could not write out edited file!", exception);
    }
}

【问题讨论】:

  • 我没有看到任何明显的错误,但我有两个建议:直接使用StandardCharsets.ISO_8859_1,也许你不需要BufferedWriter,你可以使用相同的write(String)方法OutputStreamWriter.

标签: java encoding io file-handling


【解决方案1】:

您的代码实际上没有任何问题。 Notepad++ 会看到以 UTF-8 编码的文件,因为在基本层面上,UTF-8 与您尝试使用的编码之间没有区别。与 UTF 相比,ISO 中只有特定字符不同,并且缺少一些(很多)字符。您可以阅读更多 here 或在 Google 中搜索 ISO-8859-1 vs UTF-8

I've created a simple project with your code 并使用与 ISO 编码不同的字符对其进行了测试 - 结果是 IntelliJ(可能还有 Notepad++ - 无法轻松检查,我在 Linux 上)识别为 ISO-8859-1 的文件.除此之外,我还添加了另一个类,该类利用了 Files 类的新 (JDK11) 功能。您使用的new Scanner(source, charset) 是在JDK10 中添加的,所以我认为您可能已经在使用11。这是简化的代码:

private static void editFile(File source, File target) {
    Charset charset = StandardCharsets.ISO_8859_1;
    String fileContent;
    try {
        fileContent = Files.readString(source.toPath(), charset);
    } catch (IOException exception) {
        System.err.println("Could not read input file as a single String.");
        exception.printStackTrace();
        return;
    }
    String newContent = regex(fileContent);
    try {
        Files.writeString(target.toPath(), newContent, charset);
    } catch (IOException exception) {
        System.err.println("Could not write out edited file!");
        exception.printStackTrace();
    }
}

随意克隆存储库或在 GitHub 上查看并使用您喜欢的任何代码版本。

【讨论】:

    猜你喜欢
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    相关资源
    最近更新 更多