Java 字元編碼問題
來源:互聯網
上載者:User
編碼|問題 1.關於檔案編碼
一般檔案儲存(文字檔),在儲存的時候按系統預設語言編碼(字元集)儲存, 在中文系統上是GBK,英文系統上是ISO8859_1, 日文系統上是MS932. 在開啟的時候同樣是按當前系統預設語言(字元集)編碼去解碼,所以一些中文漢字在日文系統上會顯示亂碼的原因就是這個. 說白了也就是開啟檔案時候不同平台使用的字元集不同, 例如中文字元集包括 a,b,c, 日文字元集包括a,b,當在日文系統上解碼漢字c的時候,就會出現所謂的亂碼。
2. java工作處理編碼模式
(1)java在運行期一律以unicode來儲存字元,這樣有利的支援了多語言環境.
(2)java在讀取檔案的時候預設是按照系統預設語言(字元集)編碼來解碼檔案,讀取和儲存時候的編碼不一致也導致程式中參數值錯誤,用FileInputStream類讀取檔案可以指定編碼讀取
(3)java在輸出到系統介面時(windows)會把記憶體中變數字元再通過系統預設語言(字元集)編碼去轉換,所以在輸出過程中也會碰到一系列的編碼問題
3.解決方案
(1)swing/awt : 輸出到系統介面解碼時可以通過設定組件顯示字型來替換系統字元集解碼
例如:
public static void setFont(Font pFont){
UIManager.put("Button.font", pFont);
UIManager.put("ToggleButton.font", pFont);
UIManager.put("RadioButton.font", pFont);
UIManager.put("CheckBox.font", pFont);
UIManager.put("ColorChooser.font", pFont);
UIManager.put("ToggleButton.font", pFont);
UIManager.put("ComboBox.font", pFont);
UIManager.put("ComboBoxItem.font", pFont);
UIManager.put("InternalFrame.titleFont", pFont);
UIManager.put("Label.font", pFont);
UIManager.put("List.font", pFont);
UIManager.put("MenuBar.font", pFont);
UIManager.put("Menu.font", pFont);
UIManager.put("MenuItem.font", pFont);
UIManager.put("RadioButtonMenuItem.font", pFont);
UIManager.put("CheckBoxMenuItem.font", pFont);
UIManager.put("PopupMenu.font", pFont);
UIManager.put("OptionPane.font", pFont);
UIManager.put("Panel.font", pFont);
UIManager.put("ProgressBar.font", pFont);
UIManager.put("ScrollPane.font", pFont);
UIManager.put("Viewport", pFont);
UIManager.put("TabbedPane.font", pFont);
UIManager.put("TableHeader.font", pFont);
UIManager.put("Table.font", pFont);
UIManager.put("TextField.font", pFont);
UIManager.put("PasswordFiled.font", pFont);
UIManager.put("TextArea.font", pFont);
UIManager.put("TextPane.font", pFont);
UIManager.put("EditorPane.font", pFont);
UIManager.put("TitledBorder.font", pFont);
UIManager.put("ToolBar.font", pFont);
UIManager.put("ToolTip.font", pFont);
UIManager.put("Tree.font", pFont);
}
通過傳遞一個字型名稱來控制軟體輸出的字元集,避免產生亂碼
2. JSP : 可以通過設定charset來解決
例如:<%@ page contentType="text/html;charset=gb2312" %>
3. 資料庫: java在資料庫流中也會產生編碼問題, 可以參照檔案的方法,在接收流時以特定的字元集去解碼
例如: 使用方法 InputStreamReader(InputStream in, Charset cs) 可以實現