关闭

关于国际化读取文件内容

85人阅读 评论(0) 收藏 举报
package com;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.DefaultFileSystem;
import org.apache.commons.configuration.PropertiesConfiguration;


public class test02 {


public static void main(String[] args) throws Exception {


// InputStream in= new test02().getFileByPath("aaa/ht.html",Locale.US);
//  
// byte b[]=new byte[(int)1000];     //创建合适文件大小的数组   
//        in.read(b);    //读取文件中的内容到b[]数组   
//        in.close();   
//        System.out.println(new String(b));   




Map<String,String> map= new test02().getPropertiesAll("D:/database.proPerties", Locale.CHINA);
for (String s: map.keySet()) {
System.out.println(s+"--->"+map.get(s));
}

}


/**
* 除properties意外其他文件返回

* @param filePath
* @return
* @throws ConfigurationException
*/
public InputStream getFileByPath(String filePath,Locale locale) throws ConfigurationException {



String fileSuffix=filePath.substring(filePath.lastIndexOf(".") + 1, filePath.length());
String path = filePath.substring(0,filePath.lastIndexOf(".")) + "_" + locale + "."+fileSuffix;

DefaultFileSystem def = new DefaultFileSystem();
InputStream in = def.getInputStream(fileSuffix,path);
return in;
}


/**
* 获取properties文件属性值
* @param filePath 
*aa/datavase.properties  或者 D:/datavase.properties
*aa/datavase.xml         或者 D:/datavase.xml
* @param locale
* @throws ConfigurationException
*/
public Map<String,String> getPropertiesAll(String filePath, Locale locale) throws ConfigurationException  {
// ReloadableResourceBundleMessageSource r = new ReloadableResourceBundleMessageSource();
// r.setBasename(filePath);
// r.setCacheSeconds(5);


String fileSuffix=filePath.substring(filePath.lastIndexOf(".")+1,filePath.length()).toLowerCase();
String path = filePath.substring(0,filePath.lastIndexOf(".")) + "_" + locale + "."+fileSuffix;
Configuration config;
//if(fileSuffix.equals("properties")){
config = new PropertiesConfiguration(path);
//}else if(fileSuffix.equals("xml")) {
//config = new PropertiesConfiguration(path);
//}else{
//config=null;
//}
Map<String,String> map=new HashMap<String,String>();
Iterator<String> it=config.getKeys();
   while (it.hasNext()) {
  String itnext=it.next();
  map.put(itnext, config.getString(itnext));
   }
return map;


}

}


maven依赖:

    <dependency>  
    <groupId>commons-configuration</groupId>  
    <artifactId>commons-configuration</artifactId>  
    <version>1.9</version>  
</dependency>  
<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
</dependency>


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:14775次
    • 积分:754
    • 等级:
    • 排名:千里之外
    • 原创:62篇
    • 转载:1篇
    • 译文:0篇
    • 评论:1条