关于国际化的问题在网上的很多文章,这里是昨天在处理时遇到的一个问题,需要一个内容类似这样的配置文件
派发=待审批:
转派= 代办:
这样一对一的配置自然想到了利用properties文件来处理,于是开始动手
package cn.com.ultrapower.common;
import java.io.IOException;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;
import org.apache.log4j.LogManager;
public class ProcessActionInfo {
private static Logger logger = LogManager.getLogger(ProcessActionInfo.class);
static ResourceBundle bundle;
private static Properties props = new Properties();
static{
/*try {
props.load(ProcessActionInfo.class.getResourceAsStream("action.properties"));
} catch (IOException e) {
e.printStackTrace();
}*
}
/**
* @param key
* @return
*/
public static String getValue(String key){
String strvalue = "";
Locale localeCN = new Locale("zh","EN");
bundle = ResourceBundle.getBundle("cn/com/ultrapower/common/action1",Locale.CHINA);
strvalue = bundle.getString(key);
try
{
Properties props = new Properties();
props.load(ProcessActionInfo.class.getResourceAsStream("action.properties"));
strvalue = props.getProperty(key,"待处理");
} catch (IOException e)
{
logger.info("ProcessActionInfo getValue:读取配置文件时发生异常"+e.getCause());
e.printStackTrace();
return null;
}
return strvalue;
}
public static void main(String[] args){
System.out.println( ProcessActionInfo.getValue("派发"));
}
}
代码如上,根本不能读取中文,抱错啦!ProcessActionInfo.class.getResourceAsStream("action.properties")是以iso8859-1编码读取的配置文件的,我们需要转码
在jdk/bin目录下执行命令:
native2ascii c:/action.properties c:/actiondeal.properties
会生成actiondeal.properties文件,然后可以将actiondeal.properties文件内容拷贝到action.properties中或者直接将actiondeal.properties改为actiondeal.properties以覆盖原文件
注:(action.properties文件可以位于任意目录下 )
搞定了通过Properties读取配置文件的中文问题!
java还有另一中国际化的类可以处理,但转码是必须的阿!
package cn.com.ultrapower.common;
import java.io.IOException;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
import org.apache.log4j.Logger;
import org.apache.log4j.LogManager;
public class ProcessActionInfo {
private static Logger logger = LogManager.getLogger(ProcessActionInfo.class);
static ResourceBundle bundle;
}
/**
* @param key
* @return
*/
public static String getValue(String key){
String strvalue = "";
// Locale localeCN = new Locale("zh","EN");
//bundle = ResourceBundle.getBundle("cn/com/ultrapower/common/action1",localeCN);
// bundle = ResourceBundle.getBundle("cn/com/ultrapower/common/action1",Locale.CHINA);
// bundle = ResourceBundle.getBundle("cn/com/ultrapower/common/action1",Locale.SIMPLIFIED_CHINESE);
bundle = ResourceBundle.getBundle("cn/com/ultrapower/common/action1",Locale.getDefault());
//以上几种bundle的获取方式是一样的,java会先寻找名字为action1_zh_CN.properties,如果不存在则在找action1_zh.properties,如果不存在继续找action1.properties,所以如果你的程序需要国际化,你就需要添加多个配置文件
strvalue = bundle.getString(key);
return strvalue;
}
public static void main(String[] args){
System.out.println( ProcessActionInfo.getValue("派发"));
}
}