FileReader的編碼問題


有一個UTF-8編碼的文本文件,用FileReader讀取到一個字符串,然后轉換字符集:str=new String(str.getBytes(),"UTF-8");結果大部分中文顯示正常,但最后仍有部分漢字顯示為問號!

  1. public static List<String> getLines( String fileName )  
  2. {  
  3.     List<String> lines = new ArrayList<String>();  
  4.     try  
  5.     {  
  6.         BufferedReader br = new BufferedReader(new FileReader(fileName));  
  7.         String line = null;  
  8.         while( ( line = br.readLine() ) != null )  
  9.             lines.add(new String(line.getBytes("GBK"), "UTF-8"));  
  10.         br.close();  
  11.     }  
  12.     catch( FileNotFoundException e )  
  13.     {  
  14.     }  
  15.     catch( IOException e )  
  16.     {  
  17.     }  
  18.     return lines;  
  19. }  

文件讀入時是按OS的默認字符集即GBK解碼的,我先用默認字符集GBK編碼str.getBytes(“GBK”),此時應該還原為文件中的字節序列了,然后再按UTF-8解碼,生成的字符串按理說應該就應該是正確的。

 

為什么結果中還是有部分亂碼呢?
問題出在FileReader讀取文件的過程中,FileReader繼承了InputStreamReader,但並沒有實現父類中帶字符集參數的構造函數,所以FileReader只能按系統默認的字符集來解碼,然后在UTF-8 -> GBK -> UTF-8的過程中編碼出現損失,造成結果不能還原最初的字符。

原因明確了,用InputStreamReader代替FileReader,InputStreamReader isr=new InputStreamReader(new FileInputStream(fileName),"UTF-8");這樣讀取文件就會直接用UTF-8解碼,不用再做編碼轉換。

  1. public static List<String> getLines( String fileName )  
  2. {  
  3.     List<String> lines = new ArrayList<String>();  
  4.     try  
  5.     {  
  6.         BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), "UTF-8"));  
  7.         String line = null;  
  8.         while( ( line = br.readLine() ) != null )  
  9.             lines.add(line);  
  10.         br.close();  
  11.     }  
  12.     catch( FileNotFoundException e )  
  13.     {  
  14.     }  
  15.     catch( IOException e )  
  16.     {  
  17.     }  
  18.     return lines;  
  19. }  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM