Thursday, July 28, 2011

Use OutputStreamWriter not FileWriter

Search your Java code for FileWriter and replace it with OutputStreamWriter... especially if you write UTF-8 encoded documents. You can run into a nasty problem where you develop your Java code on Linux and then when it runs on Windows, character encoding problems crop up. FileWriter uses a OS System setting to determine what encoding to use, so it will change depending on what OS runs the Java code!

Here is an example of how to use OutputStreamWriter for UTF-8 encoded output.
         OutputStreamWriter out = null;
try {
try {
out = new OutputStreamWriter(new FileOutputStream(outputFile),"UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e.getMessage,e);
}
try {
out.append(yourStringDataToWriteToOutputFile);
out.flush();
} catch (IOException e) {
throw new RuntimeException(e.getMessage,e);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e.getMessage,e);
} finally {
try {
out.close();
} catch (IOException e) {
throw new RuntimeException(e.getMessage,e);
}
}

Hope this helps you get past file character encoding bugs with Java. Here is a great link on various Java Anti-Patterns which should be avoided when writing enterprise class robust code:

No comments:

About Me

My photo
Lead Java Developer Husband and Father

Tags