properties文件第一行请空出来

问题描述:

项目启动的时候, 报出了找不到properties文件中的一个key的错误, 具体错误信息如下

java.util.MissingResourceException: Can't find resource for bundle java.util.PropertyResourceBundle. key driverClass
	at java.util.ResouceBundle.getObject(ResouceBundle.java:374) ~[na:1.6.0_38]
	at java.util.ResouceBundle.getString(ResouceBundle.java:334) ~[na:1.6.0_38]
	...
配置文件jdbc.properties如下:

driverClass = oracle.jdbc.driver.OracleDriver
userName = admin
password = 123
明明是有这个driverClass的key的, 却仍报错. 搜索了N个网站, 终于找到了问题答案: 编码!

Properties类API(http://docs.oracle.com/javase/7/docs/api/java/util/Properties.html)中提到如下一句话

The load(Reader) / store(Writer, String) methods load and store properties from and to a character based stream in a simple line-oriented format specified below. The load(InputStream) / store(OutputStream, String) methods work the same way as the load(Reader)/store(Writer, String) pair, except the input/output stream is encoded in ISO 8859-1 character encoding. Characters that cannot be directly represented in this encoding can be written using Unicode escapes as defined in section 3.3 of The Java™ Language Specification; only a single 'u' character is allowed in an escape sequence. The native2ascii tool can be used to convert property files to and from other character encodings.

大体意思是, properties文件是基于行来读取和存储键值对的, 而期望的输入/输出流字符编码是ISO 8859-1. 那些不能使用该方式存储的字符集呢, 需要使用native2ascii命令对property文件进行转码.

由于我的这个配置文件中有中文注释, 所以我使用了UTF-8的编码方式存储, 使用UTF-8存储的坏处就是会多出一些特殊字符(乱码); 使用UE在16进制下查看发现, driverClass变成了"锘縟riverClass", 当程序中再次查找driverClass时, 就会报错, 找不到key(driverClass)


解决方案一:

仍然使用UTF-8编码方式, 将第一行给空出来


再次使用UE查看, 虽然仍有乱码, 但是配置项driverClass已经正常了



解决方案二:

按照API上的指示, 使用ISO 8859-1的编码方式存储jdbc.properties文件, 中文用/u开头的unicode方式保存

如: country = 中国, 改成: country = \u4E2D\u56FD


感谢万能的谷歌, 指引我找到方向.

参考文章: http://stackoverflow.com/questions/24810028/why-does-java-ignore-the-first-line-of-a-properties-file

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值