views:

5670

answers:

4

I have a file called mybundle.txt in c:/temp -

c:/temp/mybundle.txt

how do I load this file into a java.util.resource bundle? The file is a valid resource bundle.

This does not seem to work:

java.net.URL resourceURL = null;

String path = "c:/temp/mybundle.txt";
java.io.File fl = new java.io.File(path);

try {
   resourceURL = fl.toURI().toURL();
} catch (MalformedURLException e) {    
}        

URLClassLoader urlLoader = new URLClassLoader(new java.net.URL[]{resourceURL});
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle( path , 
                java.util.Locale.getDefault(), urlLoader );

What is the best way to do this?

+5  A: 

When you say it's "a valid resource bundle" - is it a property resource bundle? If so, the simplest way of loading it probably:

FileInputStream fis = new FileInputStream("c:/temp/mybundle.txt");
try {
  return new PropertyResourceBundle(fis);
} finally {
  fis.close();
}
Jon Skeet
Hey Jon, doesn't this miss the localization issue that would be the main reason for using a bundle in the first place?
Nick Holt
There's no indication that he's actually got more than one file. The fact that it's got a .txt suffix isn't terribly encouraging. But yes, it would fail in that situation.
Jon Skeet
+1  A: 

From the JavaDocs for ResourceBundle.getBundle(String baseName):

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

What this means in plain English is that the resource bundle must be on the classpath and that baseName should be the package containing the bundle plus the bundle name, mybundle in your case.

Leave off the extension and any locale that forms part of the bundle name, the JVM will sort that for you according to default locale - see the docs on java.util.ResourceBundle for more info.

Nick Holt
A: 

I think that you want the file's parent to be on the classpath, not the actual file itself.

Try this (may need some tweaking):

String path = "c:/temp/mybundle.txt";
java.io.File fl = new java.io.File(path);

try {
   resourceURL = fl.getParentFile().toURL();
} catch (MalformedURLException e) {
   e.printStackTrace();                     
}               

URLClassLoader urlLoader = new URLClassLoader(new java.net.URL[]{resourceURL});
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("mybundle.txt", 
                java.util.Locale.getDefault(), urlLoader );
A: 

1) Change the extension to properties (ex. mybundle.properties.) 2) Put your file into a jar and add it to your classpath. 3) Access the properties using this code:

ResourceBundle rb = ResourceBundle.getBundle("mybundle");
String propertyValue = rb.getString("key");
MrPhil