天天看點

java讀取配置檔案中文亂碼

配置檔案是utf-8編碼,但是使用下面這種方式讀取出來的中文還是亂碼的:

public static void main(String[] args) throws Exception{
        Properties p = loadProperty();
        String a = p.getProperty("pro.key");
        System.out.println(a);
    }

    private static Properties loadProperty() throws IOException {
        Properties p = new Properties();
        InputStream in = null;
        try{
            in = Test.Class.getClassLoader().getResourceAsStream("sms.properties");
            p.load(in);
            return p;
        }finally {
            IOUtils.closeQuietly(in);
        }

    }
           

原因是這種流讀取方式是基于位元組的,讀取出來的字元編碼是ISO-8859-1,做一下編碼轉換即可得到正确的資料:

public static void main(String[] args) throws Exception{
        Properties p = loadProperty();
        String a = p.getProperty("pro.key");
        System.out.println(changeCharset(a,"ISO-8859-1","UTF-8"));
    }

    private static String changeCharset(String a,String charset1,String charset2){
        try {
            return new String(a.getBytes(charset1),charset2);
        } catch (UnsupportedEncodingException e) {
            throw new Error(e);
        }
    }
           

但這種方式讓代碼顯得更加繁瑣,可以直接使用reader來讀取:

private Properties loadProperty() throws IOException {
        Properties p = new Properties();
        InputStream in = null;
        BufferedReader reader = null;
        InputStreamReader sr = null;
        try{
            in = this.getClass().getClassLoader().getResourceAsStream("sms.properties");
            sr = new InputStreamReader(in);
            reader = new BufferedReader(sr);
            p.load(reader);
            return p;
        }finally {
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(sr);
            IOUtils.closeQuietly(in);
        }
    }