+-

这个问题已经在这里有了答案: > Files.readAllBytes vs Files.lines getting MalformedInputException 4个
我正在尝试使用流来读取文件,但无法通过异常.我一直在环顾四周,但我只是不明白为什么要扔它.
我正在尝试使用流来读取文件,但无法通过异常.我一直在环顾四周,但我只是不明白为什么要扔它.
我要读取的文件是file.txt,并使用UTF-8编码.
我正在使用Files.lines()阅读它:
String path = FileWordCount.class.getResource("file.txt").getPath().substring(1);
Files.lines(Paths.get(path), Charset.forName("UTF-8")).forEach(System.out::println);
尝试读取文件时,出现以下异常:
Exception in thread "main" java.io.UncheckedIOException: java.nio.charset.MalformedInputException: Input length = 1
[...]
Caused by: java.nio.charset.MalformedInputException: Input length = 1
通常,我不会发布有关异常的简单问题,但我只是想出了一个.
最佳答案
UncheckedIOException包装了MalformedInputException-这是潜在的错误. JavaDoc表示:
Checked exception thrown when an input byte sequence is not legal for
given charset, or an input character sequence is not a legal
sixteen-bit Unicode sequence.
因此,您的file.txt不包含有效的UTF-8,并导致UTF-8解码器报告错误.
点击查看更多相关文章
转载注明原文:Java 8使用流java.io.UncheckedIOException读取文件 - 乐贴网