Skip to content

Instantly share code, notes, and snippets.

@mobleyc
Created March 25, 2016 18:24
Show Gist options
  • Save mobleyc/73f1a0036d9ef3fdc7ab to your computer and use it in GitHub Desktop.
Save mobleyc/73f1a0036d9ef3fdc7ab to your computer and use it in GitHub Desktop.
Loading resource bundles in Java from property files outside of classpath, with different file extensions.
package com.cpm;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Locale;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
//ref: http://stackoverflow.com/questions/1172424/how-to-load-a-resource-bundle-from-a-file-resource-in-java
public class App {
public static void main(String[] args) throws IOException {
String currentDir = System.getProperty("user.dir");
System.out.println("Working Directory = " + currentDir);
ResourceBundle rb = fromClassLoader(currentDir, "test");
System.out.println("From bundle: key one = " + rb.getString("one"));
ResourceBundle rb2 = fromFile(currentDir, "test.pro");
System.out.println("From file: key one = " + rb2.getString("one"));
}
private static ResourceBundle fromClassLoader(String dir, String bundleName) throws MalformedURLException {
File file = new File(dir);
URL[] urls = {file.toURI().toURL()};
ClassLoader loader = new URLClassLoader(urls);
// Properties file name = test.properties. The .properties extension is appended to bundle name
return ResourceBundle.getBundle(bundleName, Locale.getDefault(), loader);
}
//This method doesn't use localization
private static ResourceBundle fromFile(String dir, String fileName) throws IOException {
FileInputStream fis = new FileInputStream(dir + "/" + fileName);
try {
return new PropertyResourceBundle(fis);
} finally {
fis.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment