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);
        }
    }

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值