FindBug: Solving DM_DEFAULT_ENCODING Warning When Using FileWriter

PROBLEM

Let’s assume we have the following code to write some data into a file:-

File file = new File(someFilePath);
Writer w = new FileWriter(file);
PrintWriter pw = new PrintWriter(w);
pw.println(someContent);
pw.close();

When running this code against a static code analysis tool, such as Findbugs, we get this high priority warning:-

Found reliance on default encoding in com.choonchernlim.epicapp.CodeGeneratorService.createFile(String): 
new java.io.FileWriter(File)

Found a call to a method which will perform a byte to String (or String 
to byte) conversion, and will assume that the default platform encoding 
is suitable. This will cause the application behaviour to vary between 
platforms. Use an alternative API and specify a charset name or Charset 
object explicitly. 

The Javadoc for FileWriter says:-

Convenience class for writing character files. The constructors of this class 
assume that the default character encoding and the default byte-buffer size are 
acceptable. To specify these values yourself, construct an OutputStreamWriter 
on a FileOutputStream.

Obviously, this class is too convenient and FindBugs is not happy about it. Further, there is no way to set a charset using FileWriter.

SOLUTION

To make FindBugs as happy as Pharrell Williams, we can use OutputStreamWriter instead because it allows us to specify a charset.

File file = new File(someFilePath);
Writer w = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
PrintWriter pw = new PrintWriter(w);
pw.println(someContent);
pw.close();

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s