如何从Java中的文件资源加载资源包?

问题描述:

我在 c中有一个名为 mybundle.txt 的文件:/ temp -

I have a file called mybundle.txt in c:/temp -

c:/temp/mybundle.txt

如何加载此文件进入 java.util.ResourceBundle ?该文件是有效的资源包。

How do I load this file into a java.util.ResourceBundle? The file is a valid resource bundle.

这似乎不起作用:

java.net.URL resourceURL = null;

String path = "c:/temp/mybundle.txt";
java.io.File fl = new java.io.File(path);

try {
   resourceURL = fl.toURI().toURL();
} catch (MalformedURLException e) {             
}           

URLClassLoader urlLoader = new URLClassLoader(new java.net.URL[]{resourceURL});
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle( path , 
                java.util.Locale.getDefault(), urlLoader );


只要您正确命名资源包文件(使用.properties扩展名),然后就可以了:

As long as you name your resource bundle files correctly (with a .properties extension), then this works:

File file = new File("C:\\temp");
URL[] urls = {file.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
ResourceBundle rb = ResourceBundle.getBundle("myResource", Locale.getDefault(), loader);

其中c:\ temp是持有该属性的外部文件夹(不在类路径上)文件,myResource与myResource.properties,myResource_fr_FR.properties等相关。

where "c:\temp" is the external folder (NOT on the classpath) holding the property files, and "myResource" relates to myResource.properties, myResource_fr_FR.properties, etc.

信用 http://www.coderanch.com/t/432762/java/java/absolute-path-bundle-file