java.util.MissingResourceException:找不到基本名称的包
我正在测试 Java 的 i18n 功能并遇到问题,当语言文件不在类根目录中时,我无法加载它。现在我的文件位于 /lang
目录中。
在 SO 中查看了几个答案,将其放入 classes
子目录中并像 lang.Messages
一样加载它,使用完整的位置路由 /Test/lang/Message (test 是项目名称),仅使用
/lang/Message
,但我仍然得到:
java.util.MissingResourceException:找不到基本名称的包
错误。
还有什么可以尝试的吗?
我的文件结构是:
Test/lang/Messages_es.properties
测试/src/test/Main.java
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
Locale currentLocale;
ResourceBundle messages;
currentLocale = new Locale("es");
messages = ResourceBundle.getBundle("Messages", currentLocale);
System.out.println(messages.getString("Messagesgreetings"));
System.out.println(messages.getString("Messagesinquiry"));
System.out.println(messages.getString("Messagesfarewell"));
}
}
I'm testing Java's i18n features and have a problem, I can't load the language file when it's not in the class root. Right now my files are in the /lang
directory.
Looked several answers here in SO, putting it in a classes
subdir and loading it like lang.Messages
, used complete location routing /Test/lang/Message
(test is the project name), using just /lang/Message
and still I'm getting the:
java.util.MissingResourceException: Can't find bundle for base name
error.
Anything else to try?
My file structure is:
Test/lang/Messages_es.properties
Test/src/test/Main.java
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
Locale currentLocale;
ResourceBundle messages;
currentLocale = new Locale("es");
messages = ResourceBundle.getBundle("Messages", currentLocale);
System.out.println(messages.getString("Messagesgreetings"));
System.out.println(messages.getString("Messagesinquiry"));
System.out.println(messages.getString("Messagesfarewell"));
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要在属性文件名中包含您的区域设置名称。
将属性文件重命名为
Messages_es.properties
由于您尚未声明任何包,因此编译后的类文件和属性文件可以位于同一根目录中。
编辑回应评论:
假设您有这个项目结构:
test\src\foo\Main.java
(foo
是包名称)test\bin \resources\Messages_es.properties
(属性文件位于类路径中的resources
文件夹中)您可以使用以下命令运行此命令:
更新的源代码:
如您所见,我们正在加载属性文件名称为“resources.Messages”
希望这有帮助。
You need to have your locale name in your properties file name.
Rename your properties file to
Messages_es.properties
Since you haven't declared any package, both your compiled class file and the properties file can be in the same root directory.
EDIT in response to comments:
Lets say you have this project structure:
test\src\foo\Main.java
(foo
is the package name)test\bin\resources\Messages_es.properties
(properties file is in the folderresources
in your classpath)You can run this with:
Updated source code:
Here as you see, we are loading the properties file with the name "resources.Messages"
Hope this helps.