我正在使用Resource bundle,并且想在运行时从其他目录将.properties文件加载到Java文件中。可能吗 ?创建可执行的JAR之后,它还能工作吗?
import java.util.Enumeration;
import java.util.ResourceBundle;
public class Test {
public static void main(String[] args) {
ResourceBundle bundle = ResourceBundle.getBundle("G:\myProject\test.properties");
Enumeration<String> enumKeys = bundle.getKeys();
while(enumKeys.hasMoreElements()){
System.out.println(enumKeys.nextElement());
}
}
}
最佳答案
使用URL类加载器将文件从目录添加到类路径:
File file = new File("G:\myProject");
URL[] urls = {file.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
ResourceBundle bundle = ResourceBundle.getBundle("test", Locale.getDefault(), loader);
Enumeration<String> enumKeys = bundle.getKeys();
while(enumKeys.hasMoreElements()){
System.out.println(enumKeys.nextElement());
}