读取文件时出现如下异常,
java.nio.charset.MalformedInputException - Input length = 1
在获取阅读器时使用以下选项有什么区别?
选项 1:
return Files.newBufferedReader(Paths.get(filePath), StandardCharsets.UTF-8);
选项 2:
return new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
选项 1 仍然返回错误,而选项 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没有这么说。这是宽松,他们决定在 Java 7 中将 NIO.2 添加到语言中时修复该缺陷。
关于java - 使用 StandardCharset UTF-8 处理格式错误的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61402450/