读取properties配置文件中文乱码

开发java项目时的配置文件:配置文件位于src同级目录(即:将项目打包为jar包后,配置文件与jar包应放于同一文件夹中)
//配置文件编码utf-8
//读取配置文件中文字符不需要重新编码
Properties properties=new Properties();
String propStr=System.getProperty("user.dir")+"\\office.properties";
InputStream url=new FileInputStream(propStr);
properties.load(new InputStreamReader(url));
 
//写入配置文件需要转码
properties.store(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(propStr)))), "utf-8");
开发Java web项目时的配置文件:配置文件位于src目录下

//配置文件编码utf-8
//读取配置文件中文需要重新编码
Properties properties = new Properties();
InputStreamReader inStream=new InputStreamReader(BaseDao.class.getClassLoader().getResourceAsStream("dao.properties"),"utf-8");
properties.load(inStream);//BaseDao为当前类
一、加载路径以及乱码问题
一般配置文件放在项目结构的src目录下,在eclipse开发环境开发Java web项目加载该配置文件的方法为:

Properties properties=new Properties();
//加载配置文件
InputStream url=Util.class.getClassLoader().getResourceAsStream("office.properties");
properties.load(new InputStreamReader(url));
有时候这样的问题在于读取中文字符时会乱码(特别是在开发java项目的时候)

虽然在往配置文件中添加数据之前,已经将配置文件编码属性修改为utf-8,但是任不可避免的会产生乱码问题。这是由于配置文件的加载默认是以ISO-8859-1编码进行,所以在读取其数据时要进行转码

String value=new String(properties.getProperty(key).getBytes("ISO-8859-1"),"utf-8");
但是将配置文件方于src目录下的方式只适合于java web开发,在jar程序开发中不能用,因为jar程序中的配置文件一般都是放于程序外部,让使用者可以修改相关配置。将配置文件置于src目录下会导致jar可执行程序在eclipse中加载成功,但在windows环境中加载失败。

将配置文件放于项目之下与src同级目录,在eclipse开发环境中加载该配置文件的方法为:

Properties properties=new Properties();
//获得配置文件目录
String propStr=System.getProperty("user.dir")+"\\*.properties";
InputStream url=new FileInputStream(propStr);
properties.load(new InputStreamReader(url));
对于properties.load()网上有的说法为:

properties.load(new InputStreamReader(url.getBytes("ISO-8859-1"),"utf-8"));
 

第一种load(没有进行转码)的做法前提是配置文件属性已经被设置为utf-8
第二种load(进行了转码)的做法前提是配置文件没有进行过属性修改(即默认编码为ISO-8859-1)
且两种做法不能互换,设置了编码为utf-8就不能使用第二种方式,默认ISO-8859-1的情况下就不能直接使用第一种方式
在进行jar可运行程序开发中,如果将配置文件放于与src同级目录,即:



导出项目后:



这种情况下对配置文件的读取和写入操作:

第一种:

//配置文件编码utf-8
//读取配置文件不需要转码
Properties properties=new Properties();
String propStr=System.getProperty("user.dir")+"\\office.properties";
InputStream url=new FileInputStream(propStr);
properties.load(new InputStreamReader(url));
 
//写入配置文件需要转码
properties.store(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(propStr)))), "utf-8");
第二种:

//配置文件编码ISO-8859-1
//读取配置文件需要转码
Properties properties=new Properties();
String propStr=System.getProperty("user.dir")+"\\office.properties";
InputStream url=new FileInputStream(propStr);
properties.load(new InputStreamReader(url.getBytes("ISO-8859-1"),"utf-8"));
 
//写入配置文件不需要转码
properties.store(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(propStr)))));

来自:https://blog.csdn.net/qq_40780805/article/details/90085681?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.control

posted @ 2021-01-10 13:35  凌晨四点lsj  阅读(1353)  评论(0编辑  收藏  举报