简体   繁体   English

如何从资源构建路径加载ResourceBundle?

[英]How can I load a ResourceBundle from my resources build path?

I have a folder containing some .properties files that I want to load into ResourceBundle. 我有一个文件夹,其中包含一些要加载到ResourceBundle中的.properties文件。 In my code, I try to pass the path of the resource folder. 在我的代码中,我尝试传递资源文件夹的路径。 However, this doesn't work since the resources are in another build path. 但是,这不起作用,因为资源在另一个构建路径中。 To clarify, I have two "source sets" one is called java and another called resources. 为了澄清,我有两个“源集”,一个叫做java,另一个叫做资源。 It does work if I move the resources into the main source folder. 如果我将资源移到主源文件夹中,它将起作用。 However, it would make more sense if I can keep the resources in the resources folder and load them with ResourceBundle.getBundle() but I haven't been able to make it work. 但是,如果我可以将资源保留在资源文件夹中并使用ResourceBundle.getBundle()加载它们,那将更有意义,但是我无法使其正常工作。 I think I need to include the resources folder in the classpath for the project but I'm just guessing. 我想我需要在项目的类路径中包含资源文件夹,但我只是在猜测。 This seems like it would be a common use case, can anyone offer some help? 这似乎是一个常见的用例,任何人都可以提供一些帮助吗?

You can use URLClassLoader from java or whatever 'ClassLoader' you are using. 您可以使用Java中的URLClassLoader或任何正在使用的“ ClassLoader”。

Sample code 样例代码

File file = new File("C:\\path\\myfile.ext");
URL[] urls = {file.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
ResourceBundle bundle = ResourceBundle.getBundle("english", Locale.getDefault(), loader);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM