java 在Java中使用ResourceBundle类时,我们可以使用属性文件指定目录路径吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3598240/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:35:29  来源:igfitidea点击:

Can we specify directory path with the property file while using ResourceBundle class in Java?

javaresourcebundle

提问by R. Rahul

I want to place my properties files in some folder, but I am not able to read them because we can specify only the bundle name in static getBundle()method on ResourceBundleobject.

我想将我的属性文件放在某个文件夹中,但我无法读取它们,因为我们只能getBundle()ResourceBundle对象的静态方法中指定包名称。

Suppose bundle is: myFile.properties
Current path is: src
I want to keep my properties file in: src/temp

假设 bundle 是:myFile.properties
当前路径是:src
我想将我的属性文件保存在:src/temp

So when I am using:

所以当我使用:

ResourceBundle.getBundle("temp/myfile", currentLocale);

it is throwing an exception "can't find bundle". I want some way to specify the path. Please suggest me some way to do this.

它抛出异常“找不到包”。我想要某种方式来指定路径。请建议我一些方法来做到这一点。

Thank you

谢谢

回答by Abhinav Sarkar

Use this:

用这个:

ResourceBundle.getBundle("temp.myfile", currentLocale);

The baseNamesupplied in the ResourceBundle.getBundlecall is supposed to be a fully qualified class name. So it has to be written separated with dots. Also note that this makes tempa package in your java code (which I don't think is a good idea). It is better to put the properties file in a proper package like com.xyz.abc. Then you can access it using

baseName在所提供的ResourceBundle.getBundle电话应该是一个完全合格的类名。所以它必须用点分开写。另请注意,这会temp在您的 Java 代码中创建一个包(我认为这不是一个好主意)。最好将属性文件放在适当的包中,例如com.xyz.abc. 然后你可以使用它访问它

ResourceBundle.getBundle("com.xyz.abc.myfile", currentLocale);

回答by McDowell

It is possible that you are using the wrong filename (myfile != myFile).

您可能使用了错误的文件名 (myfile != myFile)。

For a file myFile.propertiesin a directory tempon the classpath, this code should work:

对于类路径上myFile.properties目录中的文件temp,此代码应该有效:

ResourceBundle.getBundle("temp.myFile");