`
lclcr
  • 浏览: 124680 次
  • 性别: Icon_minigender_1
  • 来自: 山东
社区版块
存档分类
最新评论

Java实现国际化

    博客分类:
  • JAVA
阅读更多
       1.根据不同语言环境使用不同文件
       我们可以准备多个string_zh_CN.properties、string_en_US.properties等,然后根据Locale去判断当前用户的语言环境,根据不同的语言环境来使用不同的资源文件。
public class TestLocale {
	public static void main(String[] args) {
		Locale locale = Locale.getDefault();
		System.out.println(locale.getCountry());			//CN
		System.out.println(locale.getDisplayCountry());		//中国
		System.out.println(locale.getDisplayName());		//中文(中国)
		System.out.println(locale.getLanguage());			//zh
		System.out.println(locale.getDisplayLanguage());	//中文
	}
}

          然后我们就可以按照如下代码所示来选择配置文件了
Locale locale = Locale.getDefault();
String lan = locale.getLanguage();
String country = locale.getCountry();
String propsFile = "string" + lan + "_" + country + ".properties";
File file = new File(rootDir, propsFile);
FileInputStream fis = new FileInputStream(file);
Properties props = new Properties();
props.load(fis);
props.getProperty(key);

      结合FreeMarker一起使用,见FreeMarker部分。
      2.java.util.ResourceBundle
      资源包包含特定于语言环境的对象。当程序需要一个特定于语言环境的资源时,程序可以从适合当前用户语言环境的资源包中加载它。
UserInfo_en_US.properties
	username=username
	password=password
UserInfo_zh_CN.properties
	username=用户名
	password=密码

package bundle;
public class TestResourceBundle {
	public static void main(String[] args) {		
		/**
		 * ResourceBundle resource = ResourceBundle.getBundle("bundle.UserInfo", Locale.US);
		 * 
		 * remind : 为了能够输出username,资源文件必须有UserInfo_en_US.properties,否则总是使用中文资源文件
		 */
		ResourceBundle resource = ResourceBundle.getBundle("bundle.UserInfo", Locale.CHINESE);
		String name = resource.getString("username");
		try {
			name = new String(name.getBytes("ISO-8859-1"), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		System.out.println(name);
	}
}

        注意:
        (1).将UserInfo_en_US.properties、UserInfo_zh_CN.properties放在类文件同级目录下(也可以放在其他包下面,只是在ResourceBundle.getBundle时指定其所在的全限定名即可)。
        (2).中文资源文件(UserInfo_zh_CN.properties)编码方式的选择,默认是ISO-8859-1,此时需要使用java自带的工具native2ascii将中文汉字转换为ascii字符。如将"用户名"转换成"\u7528\u6237\u540d",也可以将资源文件另存为时选择编码,比如我现在的是UTF-8。
        (3).java中从资源文件中读取时采用的是ISO-8859-1编码,若已经采用(2)的方式使用了native2ascii工具则直接读取即可,否则的话要根据资源文件的编码方式进行转换。如我的中文资源文件编码为UTF-8,则读取用户名后需要重新编码name = new String(name.getBytes("ISO-8859-1"), "utf-8");
        (4).生成some.jar(TestResourceBundle、UserInfo_en_US.properties、UserInfo_zh_CN.properties),指定jar文件的main-class(bundle.TestResourceBundle), 将该jar文件拷贝到d:\test下
D:\test>java -jar some.jar
用户名		 	
D:\test>java -classpath some.jar butterfly.TestResourceBundle
用户名		 	
D:\test>

        3.java.util.PropertyResourceBundle
        PropertyResourceBundle 是 ResourceBundle 的一个具体子类,它使用属性文件中的静态字符串集来管理语言环境资源。
FileInputStream	fis = new FileInputStream(file);
PropertyResourceBundle resource = new PropertyResourceBundle(fis);
System.out.println(resource.getString("username"));

        4.参数化提示信息java.text.MessageFormat
        MessageFormat 提供了以与语言无关方式生成连接消息的方式。MessageFormat 获取一组对象,格式化这些对象,然后将格式化后的字符串插入到模式中的适当位置,使用运行时指定的参数替换一个消息字符串中的一部分。消息中的占位符字符串{0}用第一个运行时参数替换,{1}用第二个运行时参数替换,以此类推。
String messageOne = "This is the {0} directory";
System.out.println(MessageFormat.format(messageOne, "'base'"));

String messageTwo = "There is {0} files under directory {1}";
System.out.println(MessageFormat.format(messageTwo, new Object[] { 4, "'base'" }));

//System.out.println(MessageFormat.format(msg, new Object[] { "'luchunli'", "'用户'" }));
System.out.println(MessageFormat.format(msg, "'luchunli'", "'用户'"));
//输出同上,format支持可变参数

        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>>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics