項目中常常會從一些文本文件中讀取數據進行業務處理,最近遇到一個問題,另一個部門提供一個txt文本給咱們進行業務處理,當咱們使用字符流讀取文本以後,處理時,發現第一行數據沒法匹配,其餘數據能夠正常處理,第一反應是文本文件可能有問題,可能有一些不可見字符,因而把文本文件拷貝到linux上經過命令查看,發現第一行最前面多了一個<U+FEFF>,問題可能就出在這個地方了,簡單測試以下:linux
一、新建一個txt文件,文件中第一行放一個詞語"程序猿",而後保存爲UTF-8編碼:vim
二、從文本文件讀取數據,而後比較:less
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 }
三、運行程序查看結果:測試
發現讀取第一行數據,進行空格處理以後,兩個詞語不相等。編碼
四、將文件放到linux上查看(使用less命令,其餘命令可能看不到效果):spa
發現詞語以前多了一個<U+FEFF> ,問題可能就出在這個地方code
五、去掉多餘的字符blog
1)In your terminal, open the file using vim: vim file_name 2) Remove all BOM characters: :set nobomb 3) Save the file: :wq
六、用新文件覆蓋以後,再次測試就正常了。terminal
經過上面這幾步,一切都很清楚了吧。get