java - 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
对我有什么线索吗?谢谢
解决方案
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");
推荐阅读
- reactjs - 路线不工作“模板不存在”
- javascript - 如何在 Microsoft Edge 上选择和复制表格元素?(CTRL + C)
- c# - 如何在 Visual Studio 2017 社区中显示 rdlc 报告
- c++ - '
: 错误: '<insert function here>' is not a member of 'std' ' 移动源文件后 - java - firebase 可以按照我们的意愿生成一个唯一的 ID 吗?
- regex - 如何在特殊字符之前在字符串中添加\
- python-3.x - 如何从python3中的base64字符串中提取图像扩展
- android - com.google.android.gms 崩溃。服务器任务 (PingTask) 得到错误 statusCode=403
- ios - 带有取消和保存按钮操作的 Swift TimePicker 显示到 UIAlerController
- ios - 确定 UICollectionViewController / CollectionViewCell 中 CAShapeLayer 类的 CGRect 值