4

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.

The file I am going to read is file.txt and it's encoded with UTF-8.

I am reading it using 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);

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.

dabadaba
  • 9,064
  • 21
  • 85
  • 155
  • Could this be related: http://stackoverflow.com/questions/26268132/all-inclusive-charset-to-avoid-java-nio-charset-malformedinputexception-input ? – makasprzak May 10 '16 at 11:29

1 Answers1

4

The UncheckedIOException is wrapping a MalformedInputException - that is the unlying error. The JavaDoc for that says:

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.

So your file.txt does not contain valid UTF-8 and is causing the UTF-8 decoder to report an error.

isapir
  • 21,295
  • 13
  • 115
  • 116
greg-449
  • 109,219
  • 232
  • 102
  • 145