Java偏好和国际化(i18n)

use*_*750 9 java localization properties internationalization preferences

Java教程建议在Properties文件上使用Preferences API.属性文件和ResourceBundle是处理应用程序中的内部化要求的推荐方法.

我正在考虑将两者用于桌面应用程序,该应用程序将以特定于语言环境的方式显示首选项.

任何人都可以指出这种方法的问题吗?

也许我应该只使用属性文件期间?

Paw*_*yda 2

\n

我正在考虑将两者用于桌面应用程序,该应用程序将以特定于区域设置的方式显示首选项。

\n
\n\n

好的,所以您想要的是翻译后的配置文件,其形式为:

\n\n
some_translated_key=some_value\n
Run Code Online (Sandbox Code Playgroud)\n\n

好吧,除非你想支持MUI否则这应该不是什么大问题。但是,如果您这样做,以便同一台计算机上的不同用户可以使用不同的语言,或者用户可能能够切换语言,那么您在将键与属性匹配时就会遇到麻烦。在阅读密钥时,您必须扫描所有翻译,并且您最终肯定会得到同一密钥的多个条目。怎么解决呢?嗯,这是个好问题。

\n\n

根据我的经验,配置文件应该与语言无关(中立文化),并且永远不应该手动编辑(即翻译键并不重要)。

\n\n

我认为字符编码可能有问题,但以下代码片段可以正常工作(文件采用 UTF-8 编码):

\n\n
public class Main {\n    private static final String FILE_NAME = "i18ned.properties";\n    private File propertiesFile;\n    private Properties properties;\n\n    public Main() {\n        properties = new Properties();\n        propertiesFile = new File(FILE_NAME);\n        if (propertiesFile.exists()) {\n            try {\n                properties.load(new BufferedReader(new FileReader(\n                        propertiesFile)));\n            } catch (FileNotFoundException e) {\n                // not likely, but should be logged either way\n            } catch (IOException e) {\n                // logger should be used instead\n                e.printStackTrace();\n            }\n        }\n    }\n\n    public void saveProperties() {\n        try {\n            properties\n                    .store(new BufferedWriter(new FileWriter(propertiesFile)), "");\n        } catch (IOException e) {\n            // oops, use logger instead\n            e.printStackTrace();\n        }\n    }\n\n    public static void main(String[] args) {\n        Main main = new Main();\n        main.storeSome();\n        main.readSome();\n    }\n\n    private void readSome() {\n        String highAsciiKey = "\xc5\xbc\xc3\xb3\xc5\x82\xc4\x87";\n        String value = properties.getProperty(highAsciiKey);\n        System.out.println(value);\n    }\n\n    private void storeSome() {\n        String highAsciiKey = "\xc5\xbc\xc3\xb3\xc5\x82\xc4\x87";\n        String highAsciiValue = "\xc5\x82\xc4\x85k\xc4\x99";\n        properties.setProperty(highAsciiKey, highAsciiValue);\n        saveProperties();\n    }\n\n}\n
Run Code Online (Sandbox Code Playgroud)\n