0

菜鸟在这里。

我正在尝试对基于命令行的程序实施国际化。以下是 java 国际化路径中可用的内容。

import java.util.*;

public class I18NSample {

    static public void main(String[] args) {

        String language;
        String country;

        if (args.length != 2) {
            language = new String("en");
            country = new String("US");
        } else {
            language = new String(args[0]);
            country = new String(args[1]);
        }

        Locale currentLocale;
        ResourceBundle messages;

        currentLocale = new Locale(language, country);

        messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);
        System.out.println(messages.getString("greetings"));
        System.out.println(messages.getString("inquiry"));
        System.out.println(messages.getString("farewell"));
    }
}

这显然有效,但我有几个类(目前不在一个包中)。我是否需要在所有这些类中加载相同的包才能使用它们?

我想结束的是,在程序的开头,让用户选择他们想要使用的语言(从可用的 .properties 文件列表中),让他们输入将加载的命令具体文件。

这可能吗?

谢谢

4

2 回答 2

1

您可以为您的方法创建一个带有公共静态方法的辅助类getString。就像是:

public class Messages {
    private static Locale locale;

    public static void setLocale(Locale locale) {
        Messages.locale = locale;
    }

    public static String getString(String key) {
        return ResourceBundle.getBundle("MessagesBundle", locale).getString(key);
    }
}

设置消息的区域设置后,您可以通过以下方式获取消息

Messages.getString("greetings");
于 2013-10-30T15:27:47.963 回答
1

似乎没有任何理由可以说明您的所有课程都不能共享相同的LocaleResourceBundle. 我假设即使您的类并不都在同一个包中,但您会在同一个应用程序中使用它们。您只需要将它们公开或提供公共吸气剂。例如:

public class YourClass {

    private static Locale currentLocale;
    private static ResourceBundle messages;

    static public void main(String[] args) {

        String language;
        String country;

        if (args.length != 2) {
            language = new String("en");
            country = new String("US");
        } else {
            language = new String(args[0]);
            country = new String(args[1]);
        }

        currentLocale = new Locale(language, country);

        messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);
    }

    public static Locale getCurrentLocale() {
        return currentLocale;
    }

    public static ResourceBundle getMessages() {
        return messages;
    }
}

从您的其他课程中,您可以致电:

Locale currentLocale = YourClass.getCurrentLocale();
ResourceBundle messages = YourClass.getMessages();
于 2013-10-30T15:37:34.937 回答