Java读取properties文件之中文乱码问题及解决

Java读取properties文件中文乱码

初用properties,读取java properties文件的时候如果value是中文,会出现读取乱码的问题。

给定country.properties文件如下:

China=中国
USA=美国
Japan=日本
Properties properties = new Properties();  
InputStream inputStream = this.getClass().getResourceAsStream("/country.properties");  
properties.load(inputStream );  
System.out.println(properties.getProperty("China"));   

上面的程序执行后的结果会出现中文乱码,因为字节流是无法读取中文的,所以采取reader把inputStream转换成reader用字符流来读取中文。

代码如下:

Properties properties = new Properties();  
InputStream inputStream = this.getClass().getResourceAsStream("/country.properties");  
BufferedReader bf = new BufferedReader(new  InputStreamReader(inputStream));  
properties.load(bf);  
System.out.println(properties.getProperty("China")); 

两种方式读取properties配置文件

在Java中我们经常会将我们自定义的配置文件xxx.properties,读取到我们的Java代码中去。现在我目前已知有两种读取配置文件的方式,如下所示。

方式一:使用Properties集合工具类读取配置文件。

Properties的加载方法

方法名说明
void load(Reader reader)从输入字符流读取属性列表(键和元素对)
void store(Writer writer, String comments)将此属性列表(键和元素对)写入此Properties表中,一适合使用load(Reader)方法的格式写入输出字符流

加载完成后根据下面方法获取值

方法名说明
Object setProperty(String key,String value)设置集合的键和值,都是String类型,底层调用 Hashtable方法put
String getProperty(String key)使用此属性列表中指定的键搜索属性
Set<String> stringPropertyNames()从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串。

代码演示:

// properties文件略

        Properties pro = new Properties();
        int maxTotal = 0;
        int maxIdel = 0;
        String host = null;
        int port = 0;
        try {
            pro.load(new FileReader("D:\\360驱动大师目录\\Redis\\Jedis_Test\\src\\redis.properties"));
            maxTotal = Integer.parseInt(pro.getProperty("redis.maxTotal"));
            maxIdel = Integer.parseInt(pro.getProperty("redis.maxIdel"));
            host = pro.getProperty("redis.host");
            port = Integer.parseInt(pro.getProperty("redis.port"));
        } catch (IOException e) {
            e.printStackTrace();
        }

方式二:使用ResourceBundle工具类读取配置文件

ResourceBoundle加载方法

返回类型方法名描述
static ResourceBundlegetBundle(String basename)使用指定的基本名称,默认语言环境和调用者的类加载器获取资源包

加载完成后根据下面方法获取值

返回类型方法名描述
ObjectgetObject(String key)从此资源包根据键获取值,将值以Object类型返回
StringgetString(String key)从此资源包根据键获取值,将值以String类型返回
String[]getStringArray(String key)从此资源包根据键获取值,将值以列表类型返回

代码演示:

ResourceBundle bundle = ResourceBundle.getBundle("redis");
int maxTotal = Integer.parseInt(bundle.getString("redis.maxTotal"));
int maxIdel = Integer.parseInt(bundle.getString("redis.maxIdel"));
String host = bundle.getString("redis.host");
int port = Integer.parseInt(bundle.getString("redis.port"));

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文地址:https://blog.csdn.net/u013514928/article/details/85718632