【问题标题】:Reading from a file containing unmappable characters从包含不可映射字符的文件中读取
【发布时间】:2020-09-01 01:24:49
【问题描述】:

我正在尝试使用 File and Scanner 读取 .txt 文件并将其中的有用信息抓取到单独的文件中。其中一些文件包含中文字符,导致我的扫描仪抛出以下错误“java.nio.charset.UnmappableCharacterException:”。汉字不重要,如何让扫描仪忽略汉字并继续搜索文件的其余部分以获取有用的信息?

代码如下:

            try {
                File source = new File(this.parentDirectory + File.separator + this.fileName.getText());
                Scanner reader = new Scanner(source);
                StringBuilder str = new StringBuilder();
                while (reader.hasNextLine()) {
                    str.append(reader.nextLine());
                    str.append("\n");
                }
                if (reader.ioException() != null) {
                    throw reader.ioException();
                }
                reader.close();
                this.input.setText(str.toString());
            } catch (FileNotFoundException e1) {
                JOptionPane.showMessageDialog(this, "File not found!");
                return;
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

【问题讨论】:

    标签: java file-io


    【解决方案1】:

    扫描器在外部字节序列和所有 Java 字符串使用的 16 位 Unicode 字符之间进行隐式转换。

    您需要知道用于外部数据(即文件内容)的实际编码。然后你将你的 Scanner 声明为

      Scanner reader = new Scanner(file, charset);
    

    如果做得正确,那么就不应该有“不可映射”的字符了。

    如果您没有明确指定字符集,则使用平台默认值,可能是 UTF-8。

    另外,您似乎并没有真正在很大程度上使用扫描仪;你只是用它来收集线路。您可以下拉一个级别并使用 FileInputStream 将文件作为字节序列读取,并使用您认为合适的任何启发式方法来确定文件的“有用”部分。

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 2012-11-21
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多