【发布时间】: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();
}
【问题讨论】: