Skip to content

Instantly share code, notes, and snippets.

@loomismilitia
Forked from DemkaAge/UTF8Control.java
Last active May 10, 2017 10:21
Show Gist options
  • Save loomismilitia/2bf0867aef0df348520807c95d7a0dce to your computer and use it in GitHub Desktop.
Save loomismilitia/2bf0867aef0df348520807c95d7a0dce to your computer and use it in GitHub Desktop.
ResourceBundle UTF-8 Control class
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Locale;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
public class UTF8Control extends ResourceBundle.Control {
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader,
boolean reload) throws IllegalAccessException, InstantiationException, IOException {
// The below is a copy of the default implementation.
String bundleName = toBundleName(baseName, locale);
String resourceName = toResourceName(bundleName, "properties");
ResourceBundle bundle = null;
InputStream stream = null;
if (reload) {
URL url = loader.getResource(resourceName);
if (url != null) {
URLConnection connection = url.openConnection();
if (connection != null) {
connection.setUseCaches(false);
stream = connection.getInputStream();
}
}
} else {
stream = loader.getResourceAsStream(resourceName);
}
if (stream != null) {
try {
// Only this line is changed to make it to read properties files as UTF-8.
bundle = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8"));
} finally {
stream.close();
}
}
return bundle;
}
}
@loomismilitia
Copy link
Author

To load the resource bundle as utf-8 use the following:

 ResourceBundle bundle = ResourceBundle.getBundle("reports/report-resource, new Locale("pt"), new UTF8Control());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment