问题描述
我正在测试Java的i18n功能并遇到问题,当它不在类根目录中时,我无法加载语言文件。现在我的文件位于 / lang
目录中。
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.
在SO中查看了几个答案,将其放入 classes
subdir并加载它像 lang.Messages
,使用完整的位置路由 / Test / lang / Message
(test是项目名称),只使用 / lang / Message
,但我仍然得到:
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:
错误。
还有别的尝试吗?
我的文件结构是:
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"));
}
}
推荐答案
你需要在属性文件名中包含您的区域设置名称。
You need to have your locale name in your properties file name.
将属性文件重命名为 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.
编辑回应评论:
假设您有这个项目结构:
Lets say you have this project structure:
test\src\foo\Main.java
( foo
是包裹名称)
test\bin\foo\Main.class
test\bin\resources\Messages_es.properties
(属性文件位于文件夹 resources
在您的类路径中)
test\bin\resources\Messages_es.properties
(properties file is in the folder resources
in your classpath)
您可以使用以下命令运行:
You can run this with:
c:\test>java -classpath .\bin foo.Main
更新的源代码:
package foo;
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("resources.Messages", currentLocale);
System.out.println(messages.getString("Messagesgreetings"));
System.out.println(messages.getString("Messagesinquiry"));
System.out.println(messages.getString("Messagesfarewell"));
}
}
如您所见,我们正在加载属性文件名称为resources.Messages
Here as you see, we are loading the properties file with the name "resources.Messages"
希望这会有所帮助。
这篇关于java.util.MissingResourceException:找不到基本名称的包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!