All inclusive Charset to avoid “java.nio.charset.MalformedInputException: Input length = 1”?

前端 未结 10 1380
醉话见心
醉话见心 2020-11-30 00:48

I\'m creating a simple wordcount program in Java that reads through a directory\'s text-based files.

However, I keep on getting the error:

java.nio.c         


        
10条回答
  •  囚心锁ツ
    2020-11-30 01:43

    Creating BufferedReader from Files.newBufferedReader

    Files.newBufferedReader(Paths.get("a.txt"), StandardCharsets.UTF_8);
    

    when running the application it may throw the following exception:

    java.nio.charset.MalformedInputException: Input length = 1
    

    But

    new BufferedReader(new InputStreamReader(new FileInputStream("a.txt"),"utf-8"));
    

    works well.

    The different is that, the former uses CharsetDecoder default action.

    The default action for malformed-input and unmappable-character errors is to report them.

    while the latter uses the REPLACE action.

    cs.newDecoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE)
    

提交回复
热议问题