How to check if Java ResourceBundle is loaded without loading it?

I would like to check for the existence of a ResourceBundle without loading it.

Typically, I use Guice, and during initialization I want to check for existence, and at runtime I want to load it. If the package does not exist, I want to receive an early RB existence report.

If it was possible to get the ResourceBundle.Control instance used for a specific ResourceBundle, I would not have a problem getting the basic information to create the actual resource name (using toBundleName () and toResourceName ()), but this is not the case at this level.

Edit:

Ok, I found a way to do this. I will create a ResourceBundle.Control that is extensible (using custome addFormat (String, Class)) to save all package formats, and then use another method to check all possible file names for a specific locale (using the. GetResource class, as indicated below).

Coding:

class MyControl extends ResourceBundle.Control {
  private Map<String,Class<? extends ResourceBundle>> formats = new LinkedHashMap();
  public void addFormat(String format,Class<? extends ResourceBundle> rbType) {
    formats.put(format, rbType);
  }
  public boolean resourceBundleExists(ClassLoader loader, String baseName, Locale locale) {
    for (String format: formats.keySet()) {
      // for (loop on locale hierarchy) {
        if (loader.getResource(toResourceName(toBundleName(baseName, locale), format)) != null) {
          return true;
        }
      // }
    }
    return false;
  }
}
+3
source share
3 answers

If a default package must exist, you can do:

Class.getResource("/my/path/to/bundle.properties")

and it will return the file url or null if it does not exist.

Of course, use the correct class or class loader if you have a lot of them.

EDIT: if you have resources as classes you should also check

Class.getResource("/my/path/to/bundle.class")

Java 6 XML. , ResourceBundle , .

+4

, , ResourceBundle.clearCache(), .

( ), , .

, . , .properties .

, ResourceBundle.Control, , newBundle().

0

- ,

ResourceBundle bundle;
public PropertiesExist() {
    String propsFile = "log4j";
    String propsPath = this.getClass().getClassLoader().getResource(".").getPath();
    File f = new File(propsPath, propsFile + ".properties");
    if(!f.exists()){
        System.out.println("File not found!!!!");
        System.exit(-1);
    }
    bundle = ResourceBundle.getBundle(propsFile);
    System.out.println(bundle.getString("log4j.rootLogger"));
}

public static void main(String[] args) {
     new PropertiesExist();         
}

, log4.properties,

0

Source: https://habr.com/ru/post/1728276/


All Articles