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

112 lines
2.6 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 {
private static LanguageMap map;
2019-06-26 09:10:15 +00:00
private static Charset charset;
public static final int LOOP_MAX_COUNT = 1000;
2019-06-26 09:10:15 +00:00
static {
charset = Charset.forName(System.getProperty("file.encoding"));
}
2019-06-25 13:29:10 +00:00
public static void setLanguageMap(LanguageMap map) {
I18n.map = map;
}
2019-06-26 09:10:15 +00:00
public static void setEncoding(String charset) {
I18n.charset = Charset.forName(charset);
}
/** 自动从语言文件中提取翻译,空翻译时返回原键值 */
public static String translate(String key) {
return reEncode(getLanguageMapSafe().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...
*/
public 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;
}
/** 使字符串列表扁平化。 */
public static String flattenList(List<String> vlist) {
String v = "";
for(String o : vlist) {
v += o + "\n";
}
v = v.trim();
return v;
}
/**
* format
* @see #translateList(String)
*/
public static String formatList(String keyRegular, Object...format) {
return tryFormat(flattenList(translateList(keyRegular)), format);
}
2019-06-25 13:29:10 +00:00
public static boolean hasKey(String key) {
return getLanguageMapSafe().containsKey(key);
}
public static boolean canTranslate(String key) {
return hasKey(key);
}
2019-06-26 09:10:15 +00:00
private static String reEncode(String bef, Charset charset) {
byte[] bytes = bef.getBytes();
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;
}
}
private static LanguageMap getLanguageMapSafe() {
return map == null ? new LanguageMap() : map;
}
}