For example I have following code
Source.fromFile(new File( path), "UTF-8").getLines()
and it throws exception
Exception in thread "main" java.nio.charset.MalformedInputException: Input length = 1
at java.nio.charset.CoderResult.throwException(CoderResult.java:260)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:319)
I don’t care if some lines were not read, but how to skip invalid chars and continue reading lines?
You can influence the way that the charset decoding handles invalid input by calling
CharsetDecoder.onMalformedInput.Usually you won’t ever see a
CharsetDecoderobject directly, because it will be created behind the scenes for you. So if you need access to it, you’ll need to use API that allows you to specify theCharsetDecoderdirectly (instead of just the encoding name or theCharset).The most basic example of such API is the
InputStreamReader:Note that this code uses the Java 7 class
StandardCharsets, for earlier versions you can simply replace it withCharset.forName("UTF-8")(or use theCharsetsclass from Guava).