原理:Files.newBufferedReader(Path path, Charset charset)没有实现编码容错
遍历所有的字符集,读取文件,如果不报MalformedInputException,即可认为编码格式正确。
代码如下:
1 public class CharsetTest { 2 public static final Path path = Paths.get(""); 3 4 public static void main(String[] args) { 5 Mapmap = Charset.availableCharsets(); 6 List retval = map.values().stream().filter(CharsetTest::testCharset).collect(Collectors.toList()); 7 } 8 9 private static boolean testCharset(Charset charset) {10 BufferedReader br;11 try {12 br = Files.newBufferedReader(path, charset);13 } catch (IOException e) {14 System.out.println("Read file error!");15 return false;16 }17 18 try {19 while (br.readLine() != null) {20 21 }22 } catch (MalformedInputException e) {23 System.out.println("MalformedInputException");24 return false;25 } catch (IOException e) {26 System.out.println("IOException happens!");27 return false;28 }29 30 return true;31 }32 }