欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java.util.MissingResourceException: Can't find bundle for base name xxx.package.messages

程序员文章站 2022-06-08 17:22:33
...

Caused by: java.util.MissingResourceException: Can’t find bundle for base name xxx.package.messages

问题描述

在使用ResourceBundle处理国际化properties文件时

private static final ResourceBundle RESOURCE_BUNDLE 
					= ResourceBundle.getBundle(BUNDLE_NAME);

结果:

Caused by: java.util.MissingResourceException: 
Can't find bundle for base name xxx.package.messages, locale zh_CN
	at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1573)
	at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1396)
	at java.util.ResourceBundle.getBundle(ResourceBundle.java:782)

解决方案

如要读取message.properties文件

不带包名

message.properties文件放在src/main/resources下,那么

private static final String BUNDLE_NAME = "message";

带包名

如果将message.properties放在在src/main/resources某个包下,如com.example,那么:

private static final String BUNDLE_NAME = "com/example/message";

如果还是报同样的错,请检查target目录下message.properties是否真正放置正确!!

工具类

附上用ResourceBundle获取message.properties文件的工具类:

public abstract class Messages {

	//注意!! 不用带properties后缀
	//直接将message.properties放在resources/com/exmple/下
	private static final String BUNDLE_NAME = "com/example/message";
	
	//直接将message.properties放在resources下
	//private static final String BUNDLE_NAME = "message";

	private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);


	public static String getString(String key){
		try {
			return RESOURCE_BUNDLE.getString(key);
		} catch (MissingResourceException e) {
			return '!' + key + '!';
		}
	}

	public static String getString(String key, Object ...args){
		try {
			return MessageFormat.format(RESOURCE_BUNDLE.getString(key), args);
		} catch (MissingResourceException e) {
			return '!' + key + '!';
		}
	}
}

good luck !

相关标签: 代码片段