T18n/src/main/java/cn/glycol/t18n/I18n.java

97 lines
2.4 KiB
Java
Raw Normal View History

2019-06-25 13:29:10 +00:00
package cn.glycol.t18n;
2019-06-26 09:10:15 +00:00
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
2019-06-26 09:10:15 +00:00
2019-06-25 13:29:10 +00:00
public class I18n {
protected static LanguageMap map;
protected static Charset charset;
2019-06-26 09:10:15 +00:00
protected static final int LOOP_MAX_COUNT = 32767;
2019-06-26 09:10:15 +00:00
static {
map = new LanguageMap();
2019-06-26 09:10:15 +00:00
charset = Charset.forName(System.getProperty("file.encoding"));
}
2019-06-25 13:29:10 +00:00
2019-07-10 07:12:27 +00:00
/* *******************************************************
*
* Localization functions
*
* *******************************************************/
/** 自动从语言文件中提取翻译,空翻译时返回原键值 */
protected static String translate(String key) {
return reEncode(map.get(key), charset);
}
/** 自动翻译translate后再执行格式化format */
2019-06-25 13:29:10 +00:00
public static String format(String key, Object...format) {
2019-06-26 09:10:15 +00:00
return tryFormat(
translate(key),
2019-06-26 09:10:15 +00:00
format);
2019-06-25 13:29:10 +00:00
}
/**
* translate
* @param keyRegular %s0welcome.%swelcome.0welcome.1...
*/
protected static List<String> translateList(String keyRegular) {
List<String> vlist = new ArrayList<String>();
int i = 0;
while(true) {
if(i >= LOOP_MAX_COUNT) break;
String k = tryFormat(keyRegular, i);
if(hasKey(k)) {
vlist.add(translate(k));
} else {
break;
}
i++;
}
return vlist;
}
/**
* format
* @see #translateList(String)
*/
public static String formatList(String keyRegular, Object...format) {
2019-07-07 06:22:20 +00:00
return tryFormat(T18nUtils.flattenList(translateList(keyRegular)), format);
}
2019-06-25 13:29:10 +00:00
public static boolean hasKey(String key) {
return map.containsKey(key);
2019-06-25 13:29:10 +00:00
}
2019-07-10 07:12:27 +00:00
/* *******************************************************
*
* Utilities
*
* *******************************************************/
2019-06-26 09:10:15 +00:00
private static String reEncode(String bef, Charset charset) {
2019-07-10 18:40:25 +00:00
byte[] bytes = bef.getBytes(charset);
2019-06-26 09:10:15 +00:00
return new String(bytes, charset);
}
2019-06-25 13:29:10 +00:00
private static String tryFormat(String context, Object...format) {
try {
return String.format(context, format);
} catch (Exception e) {
return context;
}
}
}