Java 8使用流java.io.UncheckedIOException读取文件 [英] Java 8 read file using streams java.io.UncheckedIOException
问题描述
我正在尝试使用流来读取文件,但我无法通过异常。我一直在环顾四周,但我无法理解为什么会被抛出。
I am trying to use streams to read a file but I cannot get past an exception. I have been looking around but I just can't understand why it's being thrown.
我要读的文件是 file.txt
并且它用UTF-8编码。
The file I am going to read is file.txt
and it's encoded with UTF-8.
我正在使用 Files.lines()$ c $阅读它c>:
String path = FileWordCount.class.getResource("file.txt").getPath().substring(1);
Files.lines(Paths.get(path), Charset.forName("UTF-8")).forEach(System.out::println);
尝试阅读文件时,我收到以下异常:
When trying to read the file I am getting the following exception:
Exception in thread "main" java.io.UncheckedIOException: java.nio.charset.MalformedInputException: Input length = 1
[...]
Caused by: java.nio.charset.MalformedInputException: Input length = 1
通常情况下,我不会发布有关例外的简单问题,但我只是想出这个问题。
Normally I don't post simple questions about exceptions but I just figure this one out.
推荐答案
UncheckedIOException
正在包装 MalformedInputException
- 这是一个错误的错误。用于说明的JavaDoc:
The UncheckedIOException
is wrapping a MalformedInputException
- that is the unlying error. The JavaDoc for that says:
当给定字符集或输入的
输入字节序列不合法时,抛出检查异常字符序列不是合法的
十六位Unicode序列。
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解码器报告错误。
So your file.txt
does not contain valid UTF-8 and is causing the UTF-8 decoder to report an error.
这篇关于Java 8使用流java.io.UncheckedIOException读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!