首页 > 解决方案 > Java 资源包

问题描述

我已经好几个月没有用 Java 编程了,我有一个小应用程序要开发供我自己使用。我被困在 ResourceBundle 上!我记得它很容易使用,所以我想我的问题很容易解决,但需要新的眼光:)

Locale frLocale = new Locale("fr","CA");
Locale enLocale = new Locale("en","CA");

String dir = System.getProperty("user.dir");
System.out.println("current dir = " + dir); // current dir = D:\RP1.8.2

Path p = FileSystems.getDefault().getPath(dir,"test.properties");
System.out.println("Path : "+p.toAbsolutePath().toString()); // Path : D:\RP1.8.2\test.properties

boolean exists = Files.exists(p);
System.out.println("File found: "+exists); // File found: true

ResourceBundle bundle = ResourceBundle.getBundle(p.toAbsolutePath().toString());
/* Exception in thread "main" java.util.MissingResourceException: Can't find bundle for base name D:\RP1.8.2\test.properties, locale fr_CA */

String title = bundle.getString("main.title");
System.out.println("Titre = "+title);

所以我的属性文件存在,但 ResourceBundle 没有找到它......很奇怪。在用户目录中,我有 3 个文件:test.properties、test_fr.properties 和 test_fr_CA.properties

对我有什么线索吗?谢谢

标签: javaresourcebundle

解决方案


getBundle 的参数不是文件名,实际上也不能是文件名。ResourceBundle 文件是应用程序资源,需要放置在与编译的类相同的位置。(实际上,ResourceBundle 可以是实际的 Java 类而不是属性文件。)例如:

build
└─classes
  └─com
    └─example
      └─myapp
        ├─MyWindow.class
        ├─MyDataImporter.class
        ├─test.properties
        ├─test_fr.properties
        └─test_fr_CA.properties

代码:

ResourceBundle bundle = ResourceBundle.getBundle("com.example.myapp.test");

推荐阅读