JavaのResourceBundleを使用してヒント情報を標準化

1616 ワード

使用するいくつかのツールクラス
java.text.MessageFormat;
java.util.MissingResourceException;
java.util.ResourceBundle;
まず1つ書きます.propertiesファイルはあなたのヒント情報テンプレートとして、ここで新しいLocalStringsと申します.properties
string.fmt1=hello {0}
string.fmt2=hello {0},{1}
実験コードは次のとおりです.
public class ResourceBundleTest
{

	private static final String			BUNDLE_NAME		= "LocalStrings";
	private static final ResourceBundle	RESOURCE_BUNDLE	= ResourceBundle.getBundle(BUNDLE_NAME);

	public static String get(String key, Object... args) {
		String template = null;
		try {
			template = RESOURCE_BUNDLE.getString(key);
		} catch (MissingResourceException e) {
			StringBuilder b = new StringBuilder();
			try {
				b.append(RESOURCE_BUNDLE.getString("message.unknown"));
				b.append(": ");
			} catch (MissingResourceException e2) {
			}
			b.append(key);
			if (args != null && args.length > 0) {
				b.append("(");
				b.append(args[0]);
				for (int i = 1; i < args.length; i++) {
					b.append(", ");
					b.append(args[i]);
				}
				b.append(")");
			}
			return b.toString();
		}
		return MessageFormat.format(template, args);
	}

	public static void main(String[] args) {
		System.out.println(get("string.fmt1"," world","        "));
		System.out.println(get("string.fmt2"," world","        "));
		System.out.println(get("string.fmt21"," world","        "));
	}

}
結果:
hello  world
hello world、どうして中国語ができないの?
string.fmt 21(world、なぜ中国語にできないのか)