Files.readAllBytes vs Files.lines getting MalformedInputException
我本来以为以下两种读取文件的方法应该表现一致。但事实并非如此。第二种方法是抛出一个 .MalformedInputException
public static void main(String[] args) {
try {
String content = new String(Files.readAllBytes(Paths.get("_template.txt")));
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
try(Stream<String> lines = Files.lines(Paths.get("_template.txt"))) {
lines.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
这是堆栈跟踪:
Exception in thread "main" java.io.UncheckedIOException: java.nio.charset.MalformedInputException: Input length = 1
at java.io.BufferedReader$1.hasNext(BufferedReader.java:574)
at java.util.Iterator.forEachRemaining(Iterator.java:115)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
at java.util.stream.ReferencePipeline$Head.forEach(ReferencePipeline.java:580)
at Test.main(Test.java:19)
Caused by: java.nio.charset.MalformedInputException: Input length = 1
at java.nio.charset.CoderResult.throwException(CoderResult.java:281)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:339)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at java.io.BufferedReader$1.hasNext(BufferedReader.java:571)
... 4 more
这里有什么区别,我该如何解决?