1. 程式人生 > >JAVA Properties中文亂碼問題

JAVA Properties中文亂碼問題

如果properties檔案中存有中文字元,用以下程式碼讀取出來中文會出現亂碼:

public static String getString(String Name, String defaultValue) {
        String szRet = defaultValue;
        Properties prop = new Properties();
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(FILE_PATH);
            prop.load(fs);
            szRet = prop.getProperty(Name, defaultValue);
        } catch
(Exception e) { e.printStackTrace(); } finally { if (fs != null) { try { fs.close(); } catch (IOException e) { e.printStackTrace(); } } } return szRet; }

解決方法:
將FileInputStream改為InputStreamReader

public static String getString(String Name, String defaultValue) {
        String szRet = defaultValue;
        Properties prop = new Properties();
        InputStreamReader reader = null;
        try {
            reader =  new InputStreamReader(new FileInputStream(FILE_PATH),"utf-8"
); prop.load(reader); szRet = prop.getProperty(Name, defaultValue); } catch (Exception e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return szRet; }