Java 讀取ANSI檔案中文亂碼問題解決方式__ANSI

來源:互聯網
上載者:User

第一步:首先判斷源檔案的編碼格式:

按照給定的字元集隱藏檔時,在檔案的最開頭的三個位元組中就有可能儲存著編碼資訊,所以,基本的原理就是只要讀出檔案前三個位元組,判定這些位元組的值,就可以得知其編碼的格式。其實,如果項目啟動並執行平台就是中文作業系統,如果這些文字檔在項目內產生,即開發人員可以控制文本的編碼格式,只要判定兩種常見的編碼就可以了:GBK和UTF-8。由於中文Windows預設的編碼是GBK,所以一般只要判定UTF-8編碼格式。    對於UTF-8編碼格式的文字檔,其前3個位元組的值就是-17、-69、-65,所以,判定是否是UTF-8編碼格式的程式碼片段如下:

          File file = new File(path);          InputStream in= new java.io.FileInputStream(file);          byte[] b = new byte[3];          in.read(b);          in.close();          if (b[0] == -17 && b[1] == -69 && b[2] == -65)              System.out.println(file.getName() + ":編碼為UTF-8");          else              System.out.println(file.getName() + ":可能是GBK,也可能是其他編碼");
第二步:用指定的編碼格式讀取檔案流

[java]  view plain copy private static String forTest(String file) throws IOException {       File f = new File(file);       InputStreamReader read = new InputStreamReader(new FileInputStream(f),               "編碼格式");       BufferedReader reader = new BufferedReader(read);       String line;       String s = "";       while ((line = reader.readLine()) != null) {           s = s+line;       }       return s;   }  

 總結:就是採用如下的方式:

File file = new File("D:\\Myeclipse\\Ini\\config.properties");FileInputStream in = new FileInputStream(file);byte[] b = new byte[3];          in.read(b);          String code = "GBK";          if (b[0] == -17 && b[1] == -69 && b[2] == -65){         code = "UTF-8";          }          InputStreamReader inputStreamReader = new InputStreamReader(in,code);BufferedReader bufferedReader = new BufferedReader(inputStreamReader);String str = bufferedReader.readLine();String data = "";while(str != null){data = data + str+"\r\n";str = bufferedReader.readLine();}in.close();bufferedReader.close();System.out.println(code);System.out.println(data);







聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.