How can we fix the Reliance on default encoding
reported by findBugs:
StringBuffer printData = getPrintData(data);
try {
OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(new File(linkName)));
out.write(printData.toString());
out.flush();
final FileInputStream f = new FileInputStream(new File(linkName));
return f;
} catch (final IOException ioe) {
ioe.printStackTrace();
}
I am writing the file using StreamWriter
.
You construct OutputStreamWriter
with single argument. It means that it will convert Java string coming from printData
(which is Unicode) to byte stream (file output) using default encoding of the operating system, and you may get different results on different machines, depending on their localization settings.
For example, let's imagine that your object printData
contains Japanese text. When people run your software on Windows in Japan and US, they will get different data written into the file. US users will likely have question marks (?) replacing all hieroglyphs, while Japanese users may have UTF-8 files with original Japanese characters preserved. If the original text contains multiple languages, results will be even more unpredictable.
That may or may not be acceptable to your application, depending on what it does and where the data is coming from. That is what the warning is about.
If you know file encoding that your application should produce, you may want to explicitly choose it when constructing OutputStreamWriter
. On the other hand, if you want it to be translated into machine's default representation, leave it as is.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With