[英]How do I use ResourceBundle to avoid hardcoded config paths in Java apps?
I'd like to eliminate dependencies on hardcoded paths for configuration data in my Java apps, I understand that using ResourceBundle will help me use the classloader to find resources. 我想在我的Java应用程序中消除配置数据的硬编码路径的依赖关系,我知道使用ResourceBundle将帮助我使用类加载器来查找资源。
Can someone tell me how I would replace a hardcoded path to a resource (say a .properties configuration data file required by a class) with appropriate use of ResourceBundle? 有人能告诉我如何通过适当使用ResourceBundle来替换资源的硬编码路径(比如一个类所需的.properties配置数据文件)吗? Simple clear example if possible, thanks all.
如果可能,简单明了的例子,谢谢大家。
You will want to examine Resource.getBundle(String) . 您将需要检查Resource.getBundle(String) 。 You pass it the fully qualified name of a resource on the classpath to load as a properties file.
您将类路径上的资源的完全限定名称传递给它作为属性文件加载。
Prior to Java 6, ResourceBundle typically allowed: 在Java 6之前,ResourceBundle通常允许:
Java 6 comes with the ResourceBundle.Control class which opens the door to other sources of ResourceBundles, for example: Java 6附带了ResourceBundle.Control类,它打开了其他ResourceBundles源代码的大门,例如:
Hope this helps. 希望这可以帮助。
You don't need a ResourceBundle. 您不需要ResourceBundle。 A simple Properties object can do the job.
一个简单的Properties对象可以完成这项工作。 Just use the classloader to get an inputstream for you properties file and use it to load de values.
只需使用类加载器为您的属性文件获取输入流,并使用它来加载de值。 If you need to handle more sophisticated user configurations, use the preferences api .
如果您需要处理更复杂的用户配置,请使用首选项api 。
Kind Regards 亲切的问候
The trick behind Resource.getBundle(..) is the use of the classloader. Resource.getBundle(..)背后的技巧是使用类加载器。 You can load everything thats in your classpath by accessing it via this.getClass().getClassLoader().
您可以通过this.getClass()。getClassLoader()访问类路径中的所有内容。 Resource.getBundle(..) is a practical helper to use it in the resource/locatization topic.
Resource.getBundle(..)是在资源/ locatization主题中使用它的实用助手。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.