Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Found 'Reliance on default encoding' in OutputStream

Tags:

findbugs

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.

like image 516
Vasanth Avatar asked Feb 17 '23 20:02

Vasanth


1 Answers

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.

like image 58
Cozzamara Avatar answered Mar 04 '23 09:03

Cozzamara