properties文件的属性值为中文,读取时乱码问题

我们在开发中使用properties文件时,常会遇到这样的问题,比如说:

test.property.value=中文值

我们想把属性值设置成中文,这样无论使用@value还是直接读取出来会出现乱码,总结了两种解决方案如下:

  1. 把属性值直接转成unicode编码,写在文件中,如:
    test.property.value.unicode=\u4e2d\u6587\u503c

     

  2. 在方法中转码,如下面代码中的getChinese()方法
    package com.xiaobai.util;
    
    import lombok.extern.slf4j.Slf4j;
    
    import java.io.UnsupportedEncodingException;
    import java.util.PropertyResourceBundle;
    import java.util.ResourceBundle;
    
    
    @Slf4j
    public class PropertiesUtil {
    
        protected static ResourceBundle erpResponse;
    
        protected static final String PROPERTIES_FILE = "propertytest";
    
        static {
            try {
                erpResponse = PropertyResourceBundle.getBundle(PROPERTIES_FILE);
            } catch (Exception e) {
                log.error(PROPERTIES_FILE + "配置文件加载失败。", e);
            }
        }
    
        public static String get(String key) {
            return erpResponse.getString(key);
        }
    
        public static String getChinese(String key) {
            String string = null;
            try {
                string = new String(erpResponse.getString(key).getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage());
            }
            return string;
        }
    
        public static void main(String[] args) {
            //属性值直接写成中文,打印出来的结果:中æå¼
            System.out.println(get("test.property.value"));
            //解决方案一,使用转码的方式,打印结果:中文值
            System.out.println(getChinese("test.property.value"));
            //解决方案二,properties文件中的属性值写成unicode(\u4e2d\u6587\u503c),打印结果:中文值
            System.out.println(get("test.property.value.unicode"));
    
        }
    
    }
    

     

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值