简体   繁体   English

从 jar 中加载 ResourceBundle

[英]Loading with ResourceBundle from inside a jar

I have seen some answers concerning how to load a particular file within a jar through getResourceAsStream , and I can manage this.我已经看到了一些关于如何通过getResourceAsStream在 jar 中加载特定文件的答案,我可以管理它。 However I am facing something really specific an I could not find an answer about this on the forum.但是,我面临着一些非常具体的问题,我在论坛上找不到有关此问题的答案。

Here is the configuration:这是配置:

I have a jar file having a conf directory that contains 2 properties files messages_en_US.properties and messages_fr_FR.properties .我有一个 jar 文件,其中包含 2 个属性文件messages_en_US.propertiesmessages_fr_FR.propertiesconf目录。 The classical way to load such resources is to use加载此类资源的经典方法是使用

ResourceBundle.getBundle("messages", java.util.Locale.getDefault());

If the files were on disk, in a directory referenced by the program classpath, this works fine.如果文件在磁盘上,在程序类路径引用的目录中,这可以正常工作。 But I don't know how I can manage combining use of ResourceBundle.getBundle and use of resources from within a jar.但我不知道如何管理ResourceBundle.getBundle 的组合使用和 jar 中资源的使用。 Indeed, as I cannot see any bridge through getResourceAsStream (or this would imply managing locale by myself to specify the entire resource file name, which is not very smart).事实上,因为我无法通过getResourceAsStream看到任何桥梁(或者这意味着我自己管理语言环境以指定整个资源文件名,这不是很聪明)。

If it's in a conf directory inside the jar, then the package of the bundle you're trying to load is conf , and you should use如果它位于 jar 内的 conf 目录中,那么您尝试加载的包的包是conf ,您应该使用

ResourceBundle.getBundle("conf.messages", java.util.Locale.getDefault());

The javadoc says: javadoc说:

baseName - the base name of the resource bundle, a fully qualified class name

你试过这个吗?

ResourceBundle.getBundle("conf/messages", java.util.Locale.getDefault());

The ResourceBundle always search for a properties file, so, if you run : ResourceBundle 始终搜索属性文件,因此,如果您运行:

ResourceBundle.getBundle("messages", java.util.Locale.getDefault());

The ResourceBundle will search for the "messages.properties" in your classpath. ResourceBundle 将在您的类路径中搜索“messages.properties”。

Assuming file messages.properties is part of some xyz.jar which is already on classpath of the project where you want to use this.假设文件 messages.properties 是某个 xyz.jar 的一部分,该文件已经在您要使用它的项目的类路径上。 Packaging of this file in jar is as below:这个文件在 jar 中的打包如下:

src
   |main
       |resources
            |com
                |xyz
                   ....|message.properties 

To read this file:要读取此文件:

import java.util.ResourceBundle;

.... ....

ResourceBundle.getBundle("com.xyz.resources.messages", Locale.getDefault());

Thanks谢谢

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

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