首页 > 编程语言 >Java读取properties文件之中文乱码问题及解决

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

时间:2024-07-08 15:46:06浏览次数:15  
标签:文件 Java 读取 Properties 乱码 new properties String

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

Java技术迷

目录

Java读取properties文件中文乱码

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

给定country.properties文件如下:

?
123China=中国USA=美国Japan=日本
登录后复制 ?
1234Properties properties = new Properties();  InputStream inputStream = this.getClass().getResourceAsStream("/country.properties");  properties.load(inputStream );  System.out.println(properties.getProperty("China"));   
登录后复制

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

代码如下: 

?
12345Properties 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()从该属性列表中返回一个不可修改的键集,其中键及其对应的值是字符串。

代码演示:

?
12345678910111213141516// 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)从此资源包根据键获取值,将值以列表类型返回

代码演示:

?
12345ResourceBundle 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文件的语法有两种,一种是注释,一种属性配置。

注 释:前面加上#号

属性配置:以“键=值”的方式书写一个属性的配置信息。

  • properties文件的一个属性配置信息值可以换行,但键不可以换行。值换行用“\”表示。
  • properties的属性配置键值前后的空格在解析时候会被忽略。
  • properties文件可以只有键而没有值。也可以仅有键和等号而没有值,但无论如何一个属性配置不能没有键。

eg:

正确的资源文件格式为:

2.功能大致如下

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

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

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

3.代码演示

?
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123package 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: [email protected]");            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: [email protected]");            outputStream.close();        }        catch (IOException e)        {            e.printStackTrace();        }    } }
登录后复制

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

?
1234567891011121314151617181920212223242526272829303132333435363738391. readfile.propertiesusername=khpassword=khchinese=谓语 2. writefile.properties#author: [email protected]#Fri May 28 22:19:44 CST 2010password=khchinese=\u8C13\u8BEDusername=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=khpassword=khchinese=中文 6. writetxtfile.txtpassword=khchinese=/u4E2D/u6587username=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(“iso-8859-1”)获取获取,使用new String(data.getByte(“iso-8859-1”),”UTF-8”)进行转换。当然properties文件的编码类型需要和new String(Byte[],charst)中的第二个参数的编码类型相同

总结

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

您可能感兴趣的文章: 原文链接:https://www.jb51.net/article/271321.htm

标签:文件,Java,读取,Properties,乱码,new,properties,String
From: https://www.cnblogs.com/sunny3158/p/18290009

相关文章

  • java springboot监听事件和处理事件
    在SpringBoot中,监听和处理事件是一种常用的模式,用于在应用程序的不同部分之间传递信息。Spring的事件发布/订阅模型允许我们创建自定义事件,并在这些事件发生时由注册的监听器进行处理。这里,我将提供一个简单的SpringBoot应用程序示例,其中将包括事件的定义、事件的发布以及事件......
  • idea修改java 配置文件编码格式,验证配置项的值是否为目标编码格式
    idea修改java配置文件编码格式,验证配置项的值是否为目标编码格式实现“idea修改java配置文件编码格式”流程步骤一:打开项目配置文件首先,我们需要打开项目的配置文件,这里以使用Idea开发工具为例。步骤二:定位到配置文件找到项目目录下的src/main/resources文件夹,该文件夹一般......
  • [IDEA]修改IDEA中properties文件的默认编码格式 设置--编辑器--文件编码--UTF-8
    [IDEA]修改IDEA中properties文件的默认编码格式设置--编辑器--文件编码--UTF-8问题描述IDEA中属性文件默认编码为ISO-8859-1会出现中文乱码的情况问题解决在设置-编辑器-文件编码中,将属性文件改为utf-8原文链接:https://www.cnblogs.com/xiao-xiaoyang/p/17606006.html......
  • 基于Java中的SSM框架实现课程实验教学系统项目【项目源码+论文说明】
    摘要本课程实验教学管理系统是针对目前课程实验教学管理的实际需求,从实际工作出发,对过去的课程实验教学管理系统存在的问题进行分析,结合计算机系统的结构、概念、模型、原理、方法,在计算机各种优势的情况下,采用目前最流行的B/S结构和java中流行的MVC三层设计模式和eclipse编辑......
  • 基于Java中的SSM框架实现羽毛球交流平台系统项目【项目源码+论文说明】
    基于Java中的SSM框架实现羽毛球交流平台系统演示摘要羽毛球作为一项奥运会的比赛项目,深受人们的喜爱,是一种大众运动。随着社会的发展和人们需求的变化,羽毛球这项运动也有了一定的发展,由于其规则简单,对场地的要求也不是很高,所以有很多人选择以打羽毛球的方式强身健体,所以现......
  • Java工程中读取resources目录下properties文件的方式,从上图可知,当工程部署在服务器下
    Java工程中读取resources目录下properties文件的方式,从上图可知,当工程部署在服务器下时,配置文件以及代码都是在对应的classes文件夹下二、具体读取方法1、当需要读取当前路径下的properties文件时,即在本地没有部署到具体服务器上的情况:Filefile=newFile(“src/main/re......
  • java 读取properties java读取properties乱码,IDEA 更改显示格式
    java读取propertiesjava读取properties乱码,IDEA更改显示格式1.打开properties文件,中文呈现乱码:原因:文件格式问题,properties默认使用ISO8859-1格式,中文显示,通用的是utf-8,带中文的可改成gbk,gb2312.这里改成    utf-8即可。步骤:选中文件,右键-->properties-->resou......
  • 你真的了解Java内存模型JMM吗?
    哈喽,大家好......
  • 第一章:JAVA的环境搭建
    Java是一种计算机编程语言;除了Java编程语言,还有很多的编程语言:C,C++,C#,python等不同的编程语言类比喻不同的国家的语言;每个编程语言的语法不同java是一个用于后端开发的编程语言开发流程  ======>   了解软件应用程序市场调研:了解客户的需求/用户的需求=====>需......
  • 如何利用java依赖jave-all-deps实现视频格式转换
    视频格式转换是常见的需求,通过使用Java依赖库jave-all-deps可以实现视频格式的转换。本文将详细介绍在Java中如何利用jave-all-deps实现视频格式转换。什么是jave-all-deps库?jave-all-deps是一款基于FFmpeg库的Java音视频编解码库。它提供了一系列API,可以用来对音视频文件进......