Java实现国际化
1.根据不同语言环境使用不同文件
我们可以准备多个string_zh_CN.properties、string_en_US.properties等,然后根据Locale去判断当前用户的语言环境,根据不同的语言环境来使用不同的资源文件。
结合FreeMarker一起使用,见FreeMarker部分。
2.java.util.ResourceBundle
资源包包含特定于语言环境的对象。当程序需要一个特定于语言环境的资源时,程序可以从适合当前用户语言环境的资源包中加载它。
5.更新配置文件
在项目中,我们可以在服务器启动的时候读取配置文件中的内容到一个MAP或Cache中,当在程序中使用时就可以直接取,而不用每次都从配置文件读取,从而提高效率。
当我们在后来的某个时候修改了配置文件的话,我们就可以按照如下方式保存一个新的配置文件。实际上,我们保存过配置文件后,应该执行一次reload()方法,将现在新的配置文件的值从新加载到当前系统中。public class TestPropertiesTwo {private static Map<String, String> map = new HashMap<String, String>();static {map.put("default_password", "luchunli");map.put("min_password_length", "5");map.put("max_password_length", "20");}public static void main(String[] args) {String rootDir = "d:\\test";File file = new File(rootDir, "properties.txt");File temp = new File(rootDir, "temp.txt");FileInputStream fis = null;FileOutputStream fos = null;try {fis = new FileInputStream(file);BufferedReader br = new BufferedReader(new InputStreamReader(fis));fos = new FileOutputStream(temp);PrintWriter pw = new PrintWriter(fos);StringBuffer sbf = new StringBuffer(128);String line = null;while ((line = br.readLine()) != null) {System.out.println(line);if (line.startsWith("#")) {pw.println(line);continue;}int s = line.indexOf('=');if (s == -1) {pw.println(line);continue;}String key = line.substring(0, s);String key0 = key.replace('.', '_');String value = (String) map.get(key0);if (null == value || "".equals(value)) {pw.println(line);continue;}sbf.setLength(0);sbf.append(key);sbf.append('=');sbf.append(value);pw.println(sbf.toString());}pw.flush();pw.close();br.close();} catch (IOException e) {e.printStackTrace();} finally {if (null != fis) {try {fis.close();fos.close();} catch (IOException e) {e.printStackTrace();}}}file.delete();temp.renameTo(file);}}
<<OVER>>