aspose file tools*
The moose likes Java in General and the fly likes How to check if a given key exists in a resource bundle? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to check if a given key exists in a resource bundle?" Watch "How to check if a given key exists in a resource bundle?" New topic
Author

How to check if a given key exists in a resource bundle?

smee bond
Ranch Hand

Joined: Sep 29, 2007
Posts: 34
I want to use the following code:

ResourceBundle rb = ResourceBundle.getBundle ("sample");
String from = rb.getString("from.address");

Before getting the "value", that I want make sure the key "from.address" exists in the resource bundle. Is there a way to check if the key exists and then proceed further?
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3446
    
  12
Do you mean something like a ResourceBundle.containsKey() method ?

Edit
Whoops - just noticed my sarcasm may have been a little misplaced. That method is only available in java 1.6. If you're not using 1.6, I guess you could write your own method that does a get and returns false or null if a MissingResourceException exception is thrown.

[ December 13, 2007: Message edited by: Joanne Neal ]
[ December 13, 2007: Message edited by: Joanne Neal ]

Joanne
smee bond
Ranch Hand

Joined: Sep 29, 2007
Posts: 34
I am using 1.5, so I cannot use ResourceBundle.containsKey() I guess. Thanks for the suggestion regarding the method use.....I wanted to do something like that but is it a good practice to ask the system to throw the exception and capture it to satisfy my condition?
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3446
    
  12
I can't think of any other way off the top of my head. You could download the 1.6 jdk and have a look at the source code to see how the containsKey method is implemented.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19670
    
  18

Since all the good methods (containsKey(), keySet()) haven't been added until Java 6, there are two ways to go:

1) catch the MissingResourceException
2) use the Enumeration returned by getKeys() and check all of them.

Of course neither one is a great option.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to check if a given key exists in a resource bundle?