properties文件编码乱码问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiao__jia__jia/article/details/86557937

                            properties文件编码乱码问题

properties默认的编码格式是ISO-8859-1。
我在idea的java项目读取properties时出现了中文乱码。
只需要修改idea的编码格式
File->Settings->File Encoding


再献上我的properties读取代码

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;

public class MyPropertiesUtil {
    private static Logger logger = LoggerFactory.getLogger(MyPropertiesUtil.class);

    public static String getProperty(String pro, String key) {
        Properties properties = new Properties();
           try {
               properties.load(new InputStreamReader(MyPropertiesUtil.class.getClassLoader().getResourceAsStream(pro),"UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
               logger.error("配置文件读取异常",e);
        }
        String property = properties.getProperty(key);
        return property;
    }

    public static String getProperty(String pro, String key,String defaultValue){
        Properties properties = new Properties();
        try {
            properties.load(new InputStreamReader(MyPropertiesUtil.class.getClassLoader().getResourceAsStream(pro),"UTF-8"));
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("配置文件读取异常",e);
        }

        String value = properties.getProperty(key.trim());
        if(StringUtils.isBlank(value)){
            value = defaultValue;
        }
        return value.trim();
    }

}

猜你喜欢

转载自blog.csdn.net/xiao__jia__jia/article/details/86557937
今日推荐