读取properties文件以及解决读取时的乱码问题

读取properties文件,一般在项目中会在两种场景中用到,如下:

1、servlet中(包括struts的action,spring mvc的controller等)

//properties文件所在相对路径
String filePath = "WEB-INF\\test.properties"; 
//获取servlet的上下文  
ServletContext context = servletRequest.getServletContext(); 
String webRootPath = context.getRealPath("\\"); 
//最后得到文件的绝对路径  
String path = webRootPath+filePath ;  
InputStream inStream = new FileInputStream(new File(path));        
Properties p = new Properties();  
p.load(inStream); 
//key--value  
String value = p.getProperty("name");


2、非servlet中,例如,main方法中,junit的test方法中:// 配置文件路径    

String filePath= "test.properties";     
// 获取当前类加载的根目录,如:/C:/Program Files/Apache/Tomcat 6.0/WebContent//WEB-INF/classes/     
String path = UriFilter.class.getClassLoader().getResource("").toURI().getPath();       
// 把文件读入文件输入流   
FileInputStream fis = new FileInputStream(new File(path + filePath));        
//加载文件流的属性        
prop.load(fis); 
String value = p.getProperty("name");
System.out.println(value); 


注意:上面源代码中的test.properties文件内容为:name=测试

properties文件读取properties文件代码完毕,但是,读出来的value可能是乱码(java的中文乱码问题很常见嘛),如果你遇见了,恭喜你中奖了。那怎么解决呢?我自己采用的方式如下:

引子:一般项目中会用两个文件,一个文件是utf-8编码的,一个文件是gbk编码的,直接国际化,与国际接轨嘛(很容易理解)

方法:利用jdk提供的native2ascii.exe程序(位于jdk根路径下的bin目录中),把test.properties文件转化下(怎么转,我就不废话了),得到如下内容:name=\u6d4b\u8bd5properties\u6587\u4ef6ok,到此为止,问题解决。如果,你觉得还挺爽的话, 顶下吧,我会thank very much

猜你喜欢

转载自blog.csdn.net/nieyinyin/article/details/7469773
今日推荐