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

前端 未结 10 1369
醉话见心
醉话见心 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

    you can try something like this, or just copy and past below piece.

    boolean exception = true;
    Charset charset = Charset.defaultCharset(); //Try the default one first.        
    int index = 0;
    
    while(exception) {
        try {
            lines = Files.readAllLines(f.toPath(),charset);
              for (String line: lines) {
                  line= line.trim();
                  if(line.contains(keyword))
                      values.add(line);
                  }           
            //No exception, just returns
            exception = false; 
        } catch (IOException e) {
            exception = true;
            //Try the next charset
            if(index

提交回复
热议问题