property文件解决中文乱码
时间: 2023-09-11 13:10:08 浏览: 54
在Java中,我们可以使用Properties类来读取和写入属性文件。而要解决中文乱码的问题,我们可以采用以下两种方法:
1. 使用UTF-8编码的属性文件
在properties文件中添加以下内容:
```properties
#properties文件编码
file.encoding=UTF-8
```
然后在Java代码中读取该属性文件时,使用以下方式指定文件编码为UTF-8:
```java
Properties props = new Properties();
FileInputStream fis = new FileInputStream("config.properties");
props.load(new InputStreamReader(fis, "UTF-8"));
```
2. 使用转义字符
如果不想使用UTF-8编码的属性文件,可以在属性值中使用Unicode转义字符。
例如,将“你好”写入属性文件时,可以使用Unicode编码“\u4F60\u597D”,即:
```properties
message=\u4F60\u597D
```
在Java代码中读取该属性文件时,可以使用以下方式进行解码:
```java
Properties props = new Properties();
FileInputStream fis = new FileInputStream("config.properties");
props.load(fis);
String message = props.getProperty("message");
message = new String(message.getBytes("ISO-8859-1"), "UTF-8");
```
其中,ISO-8859-1是Java默认的字符集,通过将其转换为UTF-8来解决中文乱码问题。