i18n无法读取jar包外国际化文件的根本原因
首先我们看一下i18n是如何绑定资源文件路径的.
绑定资源文件路径的方法是通过下面方法绑定的。
ResourceBundle.getBundle()
我们查看源码:
最终发现i18n是通过类加载器加载国际化文件的。
然而类加载器是不能加载jar包外的资源文件的,所以我们要改变加载资源文件的方式,我们可以通过file加载jar包外的资源文件。
改变文件读取方式
我们读取源码发现,i18n通过将资源文件读取为stream流存储在ResourceBundle对象中,同时i18n存在缓存,将产生的stream对象存储在缓存中。
首先重写下面方法,修改i18n的读取方式。这样我们就可以读取到jar包外面的资源文件了。
private class I18nMessageSourceControl extends ResourceBundle.Control {
@Override
@Nullable
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException {
// Special handling of default encoding
if (format.equals("java.properties")) {
String bundleName = toBundleName(baseName, locale);
final String resourceName = toResourceName(bundleName, "properties");
InputStream inputStream;
try {
inputStream = AccessController.doPrivileged((PrivilegedExceptionAction<InputStream>