java读properties文件 乱码

java读properties文件,包含中文字符的主要有两种:

1.key中包含中文字符的(value中也有可能包含)

2.key中不包含中文字符的(value中有可能包含)


1、key中包含中文字符

可以使用java自带工具native2ascii.exe(Javajdk1.x.xin ative2ascii.exe),转换文件编码格式

示例: native2ascii -encoding 8859_1 c:a.properties c:.properties

即将 c:a.properties文件内容用8859_1转码,另存为c:.properties文件。

命令格式: native2ascii -[options] [inputfile [outputfile]]

参数选项 options -reverse:将 Latin-1 或 Unicode 编码转为本地编码 -encoding encoding_name:指定转换时使用的编码 inputfile:要转换的文件 outputfile:转换后的文件
互转(-encoding,非英文内容(如中文)转为编码符 或 编码符之间的转换)
逆转(-reverse,通常是将编码符转为非英文内容,或非英文内容之间的转换)
逆转时被转的文件编码和本地编码需一致:
示例: 中文转为 ISO 8859_1 编码后,将 8859_1 码转为中文:
native2ascii -encoding 8859_1 c:a.txt c:.txt,
将 a 用 8859_1 转码,存为 b (8859_1 码)
native2ascii -encoding GBK c:.txt c:c.txt,

将 b 用 GBK 转码,存为 c (GBK 码)


native2ascii -reverse c:c.txt c:d.txt,
将 GBK 编码 c 用本地编码转码,存为 d (中文内容) 中文转为 GBK 编码后,将 GBK 码转为中文:

native2ascii -encoding GBK c:a.txt c:.txt,
将 a 用 GBK 转码,存为 b (GBK 码)

native2ascii -reverse c:.txt c:c.txt,
将 GBK 编码 b 用本地编码转码,存为 c (中文内容)

做完上述操作后,读取key中含有中文的properties,需有下面的转换代码:

String value = "中国";
String value2 = new String(value.getBytes(),"ISO-8859-1");
System.out.println(p.getProperty(value2));

2.key中不包含中文字符的,value中有中文

直接使用1中的:

String value = p.getProperty(key);
String value2 = new String(value.getBytes("ISO-8859-1"),"GBK");



原文地址:https://www.cnblogs.com/signheart/p/aa08e29463686c2fc00de7ca89b8ab5b.html