ResourseBundle学习笔记"Canot find bundle for base name"

来源:互联网 发布:淘宝网花花姑娘笔袋 编辑:程序博客网 时间:2024/06/05 14:33

1.初步学习

最近在学习ResourseBundle时遇到了“Can't find bundle for base name ”这个错误搞了很久才解决了。原因就是类路径问题要将属性文件放在类路径中!百度里很多都是教程但没有涉及到解决方法! 2.中文显示:

测试文件

java 代码
  1. package com.lht.ResourseBundleStudy;   
  2.   
  3. import java.util.ResourceBundle;   
  4.   
  5. public class ResourseBundleDemo {   
  6.      public static void main(String[] args) {       
  7.      ResourceBundle resource = ResourceBundle.getBundle("test");    
  8.      System.out.print(resource.getString("msg0") + "!");     
  9.      System.out.println(resource.getString("msg1") + "!");    }   
  10.   
  11. }   

 

test.properties

 

msg0="Hello World"
msg1="da jia hao"

开始自己测试的时候:将属性文件放在bin/下也试过也不行无赖中就在google中搜索了一下终于在sun的java论坛

(http://forum.java.sun.com/thread.jspa?threadID=660477&messageID=4231534)中找到了线索下面是帖子的内容:

I've solved the problem the best way possible. Basically what i've done is added a new class folder named config to the project home dir. Then i added this classfolder to the classpath in project properties. After doing all of this you only need to reference the properties file by "Email".

Hope this helps anyone else who is having similiar problems.

基本意思就是在src下建立classes(名字无所谓)文件夹将属性文件存放在下面,然后将这个文件夹加入类路径中!运行就可以了:

加入类路径的方法:你的工程文件夹->properties->选择Libraries选项卡->Add Class Folder将刚才建立的文件夹加入就可以了!

结果如下:

"Hello World"!"da jia hao";!

 2.中文显示

在classes目录下建立message_CH.properties内容如下:

ms0="大家好"

同样用上面的测试文件!

结果如下:"?ó????"!

乱码怎么回事啊!

在百度里搜索后找到了答案有以为网友写的很清楚:http://gostar.bokee.com/3885062.html

下面引用如下:

 原理 

Property文件中,使用的编码方式根据机器本身的设置可能是GBK或者UTF-8。而在Java程序中读取Property文件的时候使用的是Unicode编码方式,这种编码方式不同会导致中文乱码。因此需要将Property文件中的中文字符转化成Unicode编码方式才能正常显示中文。 

 解决办法 

Java提供了专门的工具对Property文件进行Unicode转化,这种工具就是native2ascii,它在JDK安装环境的bin目录下。 

native2ascii 工具将带有本机编码字符(非拉丁 1 和非单一码字符)的文件转换成带有Unicode编码字符的文件。 

假设需要转化的属性文件为:D:\src\resources.properties(含有中文字符) 

转化后的属性文件为:D:\classes\resources.properties(中文字符统一转化为Unicode) 

那么使用如下命令 
JAVA_HOME\bin\native2ascii -encoding GBK D:\src\resources.properties D:\classes\resources.properties 

就能将含有中文字符的属性文件转化成单一Unicode编码方式的属性文件。中文乱码自然会被解决。

通过上面的方法我将生成的文件打开一看内容如下:

 ch="\u5927\u5bb6\u597d"

再运行结果如下:

"大家好"


摘录自:http://verran.iteye.com/blog/44357

0 0
原创粉丝点击