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

作者:追梦菜鸟 时间:2021-07-19 06:43:06 

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

Java读写资源文件类properties

Java中读写资源文件最重要的类是Properties

1.资源文件要求如下

  • properties文件是一个文本文件

  • properties文件的语法有两种,一种是注释,一种属性配置。

注 释:前面加上#号

属性配置:以&ldquo;键=值&rdquo;的方式书写一个属性的配置信息。

  • properties文件的一个属性配置信息值可以换行,但键不可以换行。值换行用&ldquo;\&rdquo;表示。

  • properties的属性配置键值前后的空格在解析时候会被忽略。

  • properties文件可以只有键而没有值。也可以仅有键和等号而没有值,但无论如何一个属性配置不能没有键。

eg:

正确的资源文件格式为:

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

2.功能大致如下

  • 读写Properties文件

  • 读写XML文件

  • 不仅可以读写上述两类文件,还可以读写其它格式文件如txt等,只要符合key=value格式即可.

Properties能读取以key,value存储的任何格式文件,看一下他的类结构就知道为什么了

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

从上面的类结构图可以看出,它继承了Hashtable并实现了Map接口

3.代码演示

package com.itbird.myhome.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

public class PropertiesMyTest
{

public static void main(String[] args)
   {

String readfile = "e:" + File.separator + "readfile.properties";
       String writefile = "e:" + File.separator + "writefile.properties";
       String readxmlfile = "e:" + File.separator + "readxmlfile.xml";
       String writexmlfile = "e:" + File.separator + "writexmlfile.xml";
       String readtxtfile = "e:" + File.separator + "readtxtfile.txt";
       String writetxtfile = "e:" + File.separator + "writetxtfile.txt";

readPropertiesFile(readfile); //读取properties文件
       writePropertiesFile(writefile); //写properties文件
       readPropertiesFileFromXML(readxmlfile); //读取XML文件
       writePropertiesFileToXML(writexmlfile); //写XML文件
       readPropertiesFile(readtxtfile); //读取txt文件
       writePropertiesFile(writetxtfile); //写txt文件
   }

//读取资源文件,并处理中文乱码
   public static void readPropertiesFile(String filename)
   {
       Properties properties = new Properties();
       try
       {
           InputStream inputStream = new FileInputStream(filename);
           properties.load(inputStream);
           inputStream.close(); //关闭流
       }
       catch (IOException e)
       {
           e.printStackTrace();
       }
       String username = properties.getProperty("username");
       String passsword = properties.getProperty("password");
       String chinese = properties.getProperty("chinese");
       try
       {
           chinese = new String(chinese.getBytes("ISO-8859-1"), "GBK"); // 处理中文乱码
       }
       catch (UnsupportedEncodingException e)
       {
           e.printStackTrace();
       }
       System.out.println(username);
       System.out.println(passsword);
       System.out.println(chinese);
   }

//读取XML文件,并处理中文乱码
   public static void readPropertiesFileFromXML(String filename)
   {
       Properties properties = new Properties();
       try
       {
           InputStream inputStream = new FileInputStream(filename);
           properties.loadFromXML(inputStream);
           inputStream.close();
       }
       catch (IOException e)
       {
           e.printStackTrace();
       }
       String username = properties.getProperty("username");
       String passsword = properties.getProperty("password");
       String chinese = properties.getProperty("chinese"); //XML中的中文不用处理乱码,正常显示
       System.out.println(username);
       System.out.println(passsword);
       System.out.println(chinese);
   }

//写资源文件,含中文
   public static void writePropertiesFile(String filename)
   {
       Properties properties = new Properties();
       try
       {
           OutputStream outputStream = new FileOutputStream(filename);
           properties.setProperty("username", "myname");
           properties.setProperty("password", "mypassword");
           properties.setProperty("chinese", "中文");
           properties.store(outputStream, "author: shixing_11@sina.com");
           outputStream.close();
       }
       catch (IOException e)
       {
           e.printStackTrace();
       }
   }

//写资源文件到XML文件,含中文  
   public static void writePropertiesFileToXML(String filename)
   {
       Properties properties = new Properties();
       try
       {
           OutputStream outputStream = new FileOutputStream(filename);
           properties.setProperty("username", "myname");
           properties.setProperty("password", "mypassword");
           properties.setProperty("chinese", "中文");
           properties.storeToXML(outputStream, "author: shixing_11@sina.com");
           outputStream.close();
       }
       catch (IOException e)
       {
           e.printStackTrace();
       }
   }

}

运行本程序所需的资源文件,我是放在E盘根目录,如E:/readfile.properties

1. readfile.properties
username=kh
password=kh
chinese=谓语

2. writefile.properties
#author: shixing_11@sina.com
#Fri May 28 22:19:44 CST 2010
password=kh
chinese=\u8C13\u8BED
username=kh

3. readxmlfile.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="password">mypassword</entry>
<entry key="chinese">中文</entry>
<entry key="username">myname</entry>
</properties>

4. writexmlfile.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="password">kh</entry>
<entry key="chinese">中文</entry>
<entry key="username">kh</entry>
</properties>

5. readtxtfile.txt    
username=kh
password=kh
chinese=中文

6. writetxtfile.txt
password=kh
chinese=/u4E2D/u6587
username=kh

4.Properties获取数据乱码解决

1.原因

Properties调用load(InputStream)时,读取文件时使用的默认编码为ISO-8859-1;当我们讲中文放入到properties文件中,通过getProperty(key)获取值时,取到得数据是ISO-8859-1格式的,但是ISO-8859-1是不能识别中文的。

2.解决方法

通过getProperty()获取的数据data既然是ISO-8859-1编码的,就通过data.getByte(&ldquo;iso-8859-1&rdquo;)获取获取,使用new String(data.getByte(&ldquo;iso-8859-1&rdquo;),&rdquo;UTF-8&rdquo;)进行转换。当然properties文件的编码类型需要和new String(Byte[],charst)中的第二个参数的编码类型相同

来源:https://blog.csdn.net/u013514928/article/details/85718632

标签:Java,properties,中文乱码
0
投稿

猜你喜欢

  • SpringBoot接口中如何直接返回图片数据

    2023-04-22 13:10:24
  • 图文并茂讲解RocketMQ消息类别

    2023-06-11 07:59:41
  • SpringMVC的执行流程及组件详解

    2021-06-17 23:29:21
  • C#控制图像旋转和翻转的方法

    2023-11-26 08:25:08
  • Android 应用中插入广告的实例

    2023-02-15 22:41:34
  • 解析C++哈夫曼树编码和译码的实现

    2021-11-19 05:26:25
  • MyBatis注解CRUD与执行流程深入探究

    2023-07-03 06:19:44
  • c#固定长度的随机字符串例子

    2021-10-24 06:11:10
  • 基于c#用Socket做一个局域网聊天工具

    2023-08-17 09:36:14
  • java字符串常用操作方法(查找、截取、分割)

    2023-11-29 03:21:13
  • java自动装箱拆箱深入剖析

    2023-09-03 08:45:19
  • Android实现Banner界面广告图片循环轮播(包括实现手动滑动循环)

    2022-02-06 17:05:35
  • SpringBoot使用WebSocket的方法实例详解

    2022-12-26 03:19:25
  • Mybatis配置之<typeAliases>别名配置元素解析

    2023-08-02 03:09:54
  • C#中out保留字用法实例分析

    2021-07-28 18:44:54
  • RocketMQ之Consumer整体介绍启动源码分析

    2022-06-04 03:53:31
  • SpringMVC记录我遇到的坑_AOP注解无效,切面不执行的解决

    2021-08-09 06:20:58
  • android shape实现阴影或模糊边效果

    2022-10-14 02:01:09
  • Spring Boot实现分布式系统中的服务发现和注册(最新推荐)

    2022-07-10 03:50:23
  • springboot+chatgpt+chatUI Pro开发智能聊天工具的实践

    2023-10-30 05:38:03
  • asp之家 软件编程 m.aspxhome.com