Java tutorial
package iqq.app.core.service.impl; import iqq.app.core.service.I18nService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.io.*; import java.text.MessageFormat; import java.util.*; /** * ???resources/i18nappBundle * * Project : iqq-projects * Author : < 6208317@qq.com > * Created : 14-4-17 * License : Apache License 2.0 */ @Service public class I18nServiceImpl implements I18nService { private static final Logger LOG = LoggerFactory.getLogger(I18nServiceImpl.class); /** * ??? */ public static final String I18N_BUNDLE = "appBundle"; /** * ? */ public static final String I18N_DIR = System.getProperty("app.dir", System.getProperty("user.dir")) + File.separator + "resources" + File.separator + "i18n" + File.separator; private Map<String, ResourceBundle> resourceBundleMap = new HashMap<String, ResourceBundle>(); /** * ??? * * @param messageKey * @return */ @Override public String getMessage(String messageKey) { return getMessage(messageKey, getCurrentLocale()); } /** * ????? * * @param messageKey * @param params * @return */ @Override public String getMessage(String messageKey, Object... params) { return getMessage(messageKey, getCurrentLocale(), params); } /** * ??? * * @param messageKey * @param locale * @return */ @Override public String getMessage(String messageKey, Locale locale) { return getResourceBundle(locale).getString(messageKey); } /** * ????? * * @param messageKey * @param locale * @param params * @return */ @Override public String getMessage(String messageKey, Locale locale, Object... params) { String message = getMessage(messageKey, locale); if (message != null && params != null) { message = MessageFormat.format(message, params); } return message; } /** * ?? * * @return */ @Override public Locale getCurrentLocale() { return Locale.getDefault(); } /** * ?? * * @return */ @Override public String getI18nDirectory() { return I18N_DIR; } private ResourceBundle getResourceBundle(Locale locale) { BufferedInputStream bis = null; try { // ??_?_?.properties String flag = locale.getLanguage() + "_" + locale.getCountry(); String filename = I18N_DIR + I18N_BUNDLE + "_" + flag + ".properties"; ResourceBundle resourceBundle = resourceBundleMap.get(flag); // ??? if (resourceBundle != null) return resourceBundle; if (!new File(filename).exists()) { filename = I18N_DIR + I18N_BUNDLE + ".properties"; } LOG.debug(filename); bis = new BufferedInputStream(new FileInputStream(filename)); resourceBundle = new PropertyResourceBundle(bis); resourceBundleMap.put(flag, resourceBundle); return resourceBundle; } catch (FileNotFoundException e) { LOG.error("?", e); } catch (IOException e) { LOG.error("??", e); } finally { if (bis != null) try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } }