-
-
Save milovtim/5b64609b04c2b3a2bff74289a3b3ef21 to your computer and use it in GitHub Desktop.
Loading resource bundles in Java from property files outside of classpath, with different file extensions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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