https://www.cnblogs.com/jessezeng/p/6729690.html
項目中經常會從一些文本文件中讀取數據進行業務處理,最近遇到一個問題,另外一個部門提供一個txt文本給我們進行業務處理,當我們使用字符流讀取文本之後,處理時,發現第一行數據無法匹配,其他數據可以正常處理,第一反應是文本文件可能有問題,可能有一些不可見字符,於是把文本文件拷貝到linux上通過命令查看,發現第一行最前面多了一個<U+FEFF>,問題可能就出在這個地方了,簡單測試如下:
1、新建一個txt文件,文件中第一行放一個詞語"程序猿",然後保存爲UTF-8編碼:
2、從文本文件讀取數據,然後比較:
1 public static void main(String[] args) throws Exception { 2 String firstline=readFirstLine("wordFile.txt"); 3 System.out.println(firstline.trim()); 4 System.out.println("程序猿".equals(firstline)); 5 6 } 7 8 private static String readFirstLine(String filename)throws Exception{ 9 try( 10 BufferedReader reader=new BufferedReader(new FileReader(new File(ClassLoader.getSystemResource(filename).getPath()))); 11 ){ 12 String str=null; 13 while((str=reader.readLine())!=null){ 14 return str; 15 } 16 } 17 return null; 18 }
3、運行程序查看結果:
發現讀取第一行數據,進行空格處理之後,兩個詞語不相等。
4、將文件放到linux上查看(使用less命令,其他命令可能看不到效果):
發現詞語之前多了一個<U+FEFF> ,問題可能就出在這個地方
5、去掉多餘的字符
1)In your terminal, open the file using vim: vim file_name 2) Remove all BOM characters: :set nobomb 3) Save the file: :wq
6、用新文件覆蓋之後,再次測試就正常了。
通過上面這幾步,一切都很清楚了吧。