Showing posts with label i18n. Show all posts
Showing posts with label i18n. Show all posts

1/4/08

Goodbye ASCII; Hello Unicode - Part Two

Want to write Unicode to a file? Say no more:

public void write(String stuff, String toFilename) 
throws IOException
{
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter theFile = null;

try
{
fos = new FileOutputStream(toFilename);
osw = new OutputStreamWriter(fos, "utf-8");
theFile = new BufferedWriter(osw);
theFile.write(stuff);
theFile.flush();
}
finally
{
try
{
if (fos != null)
{
fos.close();
}

if (osw != null)
{
osw.close();
}

if (theFile != null)
{
theFile.close();
}
}
catch (IOException ignored)
{
log4jLogger.error(ignored);
}
}
}

Goodbye ASCII; Hello Unicode

Sometime, when you actually have to write internationalized software, you may run into difficulties with those damned ResourceBundles, and their bastard progeny, the PropertyResourceBundle.

According to the documentation, "(c)onstructing a PropertyResourceBundle instance from an InputStream requires that the input stream be encoded in ISO-8859-1."

If you end up with non-ISO-8859-1 characters in your bundle (e.g., SimplifiedChinese and Japanese), all is not lost. The little trick I stole from this guy could save you an awful lot of grief:

public String getProperty(String key)
{
ResourceBundle bundle = getResourceBundle();
String value = bundle.get(key);
byte[] bytes = value.getBytes("ISO-8859-1");
return new String(bytes, "utf-8");
}