java读取TXT文件(硬核区分编码格式)

时间:2021-08-16
本文章向大家介绍java读取TXT文件(硬核区分编码格式),主要包括java读取TXT文件(硬核区分编码格式)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

废话:我看了百度上大部分的自动读取TXT文件,在不确定编码格式的情况下,好像都没啥效果,但是我还是保留了,万一有用呢[狗头],可能是我的搜索方式不对,没有找到正确结果,我目前的方法由于太过硬核我也觉得不是很好,如果有更好的方法,望告知,先谢谢啦

原理:实现原理真的很粗暴,我把几乎所有汉字的utf8编码的byte数组统计了一下范围,一个utf8字符占3个字节,就比对文件中第一个汉字是否符合utf8的三个字节,但是缺点也很明显,肯定会有没有涵盖到的,别问为什么只区分utf8,因为只有utf8编码还算有规律

 1 public static String readTxtFile(String filePath){
 2         try {
 3             File file=new File(filePath);
 4             if(file.isFile() && file.exists()){ //判断文件是否存在
 5                 InputStream inputStream = new FileInputStream(file);
 6                 byte[] head = new byte[3];
 7                 inputStream.read(head);
 8                 String code = "GBK";
 9                 if (head[0] == -1 && head[1] == -2){
10                     code = "UTF-16";
11                 }else if (head[0] == -2 && head[1] == -1){
12                     code = "Unicode";
13                 }else if (head[0] == -17 && head[1] == -69 && head[2] == -65){
14                     code = "UTF-8";
15                 }else{
16                     byte[] text = new byte[(int)file.length()];
17                     System.arraycopy(head,0,text,0,3);
18                     inputStream.read(text,3,text.length-3);
19                     for (int i = 0; i < text.length; i++) {
20                         int a = text[i]&0xFF;
21                         int b = text[i+1]&0xFF;
22                         if (a>0x7F){//排除开头的英文或者数字字符
23                             if (0xE3<a&a<0xE9&&b>0x7F&&b<0xC0){//符合utf8
24                                 code = "UTF-8";
25                                 break;
26                             }else break;
27                         }
28                     }
29                 }
30                 System.out.println(code);
31                 InputStreamReader read = new InputStreamReader(
32                         new FileInputStream(file),code);//考虑到编码格式
33                 BufferedReader bufferedReader = new BufferedReader(read);
34                 String lineTxt;
35                 String res = "";
36                 while((lineTxt = bufferedReader.readLine()) != null){
37                     //System.out.println(lineTxt);
38                     res += lineTxt;
39                 }
40                 read.close();
41                 return res;
42             }else{
43                 System.out.println("找不到指定的文件");
44             }
45         } catch (Exception e) {
46             System.out.println("读取文件内容出错");
47             e.printStackTrace();
48         }
49         return null;
50     }

所以,有更好的方法要告诉我啊

原文地址:https://www.cnblogs.com/duojiao/p/15149304.html