首页 > 其他 > 详细

使用1.7 Files,实现编码探测

时间:2019-07-09 09:36:42      阅读:90      评论:0      收藏:0      [点我收藏+]

原理: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         Map<String, Charset> map = Charset.availableCharsets();
 6         List<Charset> 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 }

 

使用1.7 Files,实现编码探测

原文:https://www.cnblogs.com/blouson/p/11155213.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!