【Java开源代码栏目提醒】:网学会员--在 Java开源代码编辑为广大网友搜集整理了:Utilities.java绩等信息,祝愿广大网友取得需要的信息,参考学习。
package resources;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Hashtable;
/**
* 多语言资源读取类
*
* @author 白胜普
* @version 1.00
*/
public class Utilities {
// 类静态实例
private static Utilities _instance = null;
// 英文资源保存Hashtable实例
public Hashtable textRepositoryForEN = new Hashtable();
// 中文简体资源保存Hashtable实例
public Hashtable textRepositoryForCN = new Hashtable();
// 资源文件根目录
public static String Res_Directory = "C://book//Tool//eclipse//workspace//Struts2RFT4//resources//";
// 静态实例函数
public static Utilities getInstance() {
if (null == _instance)
_instance = new Utilities();
return _instance;
}
/**
* 构造函数
*/
public Utilities() {
// 将英文资源文件数据保存到Hashtable中
saveToHashtable("en", textRepositoryForEN, Res_Directory
+ "ApplicationResources_en.properties");
// 将中文简体资源文件数据保存到Hashtable中
saveToHashtable("zh-cn", textRepositoryForCN, Res_Directory
+ "ApplicationResources_zh_CN.properties");
}
/**
* 根据关键值取得资源
*/
public String getLocalText(String locale, String textId) {
if (locale.equals("en"))
return (String) textRepositoryForEN.get(textId);
else if (locale.equals("zh-cn"))
return (String) textRepositoryForCN.get(textId);
return null;
}
/**
* 将资源文件数据保存到Hashtable中
*/
public void saveToHashtable(String language, Hashtable hashtable,
String fileName) {
// 局部变量定义
BufferedReader in = null;
String temp = new String();
String s = "";
String acturalValue = "";
int i = 0;
try {
// 读取资源文件
in = new BufferedReader(new FileReader(fileName));
while ((temp = in.readLine()) != null) {
// 如果不是注释行,保存该行数据到Hashtable
if (!"#".equals(temp.substring(0, 1))) {
i = temp.indexOf("=");
if (language.equals("zh-cn")) {
// Unicode转化成GB的源码
s = UnicodetoGB(temp.substring(i + 1));
acturalValue = new String(s.getBytes(), "GBK");
} else {
acturalValue = temp.substring(i + 1);
}
// 保存资源到Hashtable
hashtable.put(temp.substring(0, i), acturalValue);
}
}
} catch (Exception e) {
// 异常抛出
System.err.println("Reading file data fails.");
} finally {
try {
if (null != in) {
in.close();
}
} catch (Exception e) {
System.err.println("BufferedReader object close fails.");
}
}
}
/**
* Unicode转化成GB的源码
*/
public String UnicodetoGB(String s) {
StringBuffer sb = new StringBuffer();
boolean escape = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '\\':
escape = true;
break;
case 'u':
case 'U':
if (escape) {
try {
sb.append((char) Integer.parseInt(s.substring(i + 1,
i + 5), 16));
escape = false;
} catch (NumberFormatException e) {
System.out
.println("DealString::UnicodetoGB(String)运行出错:"
+ e + "抛出IllegalArgumentException异常.");
throw new IllegalArgumentException();
}
i += 4;
} else {
sb.append(c);
}
break;
default:
sb.append(c);
break;
}
}
return sb.toString();
}
}