IO流和Properties联合使用解决中文乱码问题
简述
- Map集合key value
- 经常改变的数据,可以单独写到一个文件中---------配置文件
- key=value文件
- 配置文件,建议以.properties结尾,但不是必须的
- 以.properties结尾的文件,被称为:属性配置文件
- Properties是专门存放配置文件的一个类
- 使用load()方法读取
- 优点:以后只需要修改文件内容,不需要改动代码,就能够拿到动态的信息
举例:读取配置文件
配置文件
- 文件名
- Test.properties
username=zhang san
####在属性配置文件中‘#’是注释########
#####key重复,value会覆盖###########
password=123455677
password=000000000
########最好等号两边无空格##########
########使用冒号也可以但是,不建议###
password:1111111111
message=张三
name=李四
编写代码
- 这里的文件是位于 src\Properties\Test.properties
- 这个路径是相对路径
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class PropertiesTest {
public static void main(String[] args) {
//新建输入流
FileReader fr = null;
try {
fr = new FileReader("src\\Properties\\Test.properties");
//新建Map集合
Properties pro = new Properties();
//调用的是load方法--传入一个输入流
pro.load(fr);
//通过Key获取value
System.out.println(pro.getProperty("username"));//zhang san
System.out.println(pro.getProperty("password"));//1111111111
//System.out.println(pro.getProperty("message"));中文乱码
//以下代码为尝试解码-------无法解决
String s = new String(pro.getProperty("message"));
String s1= new String(s.getBytes("ISO-8859-1"),"gbk");
System.out.println(s);//����
System.out.println(s1);//????
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
问题发现
- 查阅资料发现
- properties文件默认的用的GBK编码的,所以需要用GBK解码
- 网上我也搜索解决方案,但是都无法解决
重点
- 值得注意的是,Properies集合的load()方法只能传入的是字符流
- 而InputStreamReader能够将字节流转换成字符流
- 同时它有一个带参构造
InputStreamReader(InputStream in, CharsetDecoder dec)
其中CharsetDecoder被称为字符解码器
dec可以传入一个字符解码器
使用GBK解码
解决乱码问题
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
public class PropertiesTest01 {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("src\\Properties\\Test.properties");
Properties properties = new Properties();
//properties.load(fis);//只能传入Reader对象,转换一下,传入字符流
//System.out.println(properties.getProperties("message"));//出错---无此方法
InputStreamReader isr = new InputStreamReader(fis, "GBK");//传入编码方式
properties.load(isr);
System.out.println(properties.getProperty("message"));//输出正确---张三
System.out.println(properties.getProperty("name"));//李四
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
总结
经过字节流–>字符流的转换,成功解决了中文乱码问题
以上若有错误,欢迎批评指正!
本人是正在自学java的小白,刚刚建立了个人博客,欢迎光顾!
网住:我的个人博客欢迎点击
https://equinoxes.gitee.io/