使用 StandardCharset UTF-8 处理畸形异常
Using StandardCharset UTF-8 for Malformed Exception
如果读取文件时出现如下异常,
java.nio.charset.MalformedInputException - Input length = 1
在获取 Reader 时使用以下选项有什么区别?
选项 1:
return Files.newBufferedReader(Paths.get(filePath), StandardCharsets.UTF-8);
选项 2:
return new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
选项 1 仍然 returns 错误,而 选项 2 通过。这两个选项有何不同?
How are both options different?
它们是不同的,因为 Files.newBufferedReader(Path path, Charset cs)
的 javadoc 说:
The Reader methods that read from the file throw IOException if a malformed or unmappable byte sequence is read.
InputStreamReader
的 javadoc 没有这么说。它是 lenient,他们决定在将 NIO.2 添加到 Java 7.
中的语言时修复该缺陷
如果读取文件时出现如下异常,
java.nio.charset.MalformedInputException - Input length = 1
在获取 Reader 时使用以下选项有什么区别?
选项 1:
return Files.newBufferedReader(Paths.get(filePath), StandardCharsets.UTF-8);
选项 2:
return new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
选项 1 仍然 returns 错误,而 选项 2 通过。这两个选项有何不同?
How are both options different?
它们是不同的,因为 Files.newBufferedReader(Path path, Charset cs)
的 javadoc 说:
The Reader methods that read from the file throw IOException if a malformed or unmappable byte sequence is read.
InputStreamReader
的 javadoc 没有这么说。它是 lenient,他们决定在将 NIO.2 添加到 Java 7.