Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Found reliance on default encoding: new java.io.FileWriter(File, boolean)

I'm using FileWrite class to write into a file.and its working fine. But FindBugs is pointing me a Minor issue in my code snippet.

code snippet:

  SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
        Date now = new Date();
        String fileName = formatter.format(now) + ".txt";
        FileWriter writer = null;
        try {
            File root = new File(Environment.getExternalStorageDirectory(), "Test");
            if (!root.exists()) {
                root.mkdirs();
            }
            File gpxfile = new File(root, fileName);

            writer = new FileWriter(gpxfile, true);
            writer.append(text + "\n\n");

        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            if (writer != null) {
                try {
                    writer.flush();
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

Findbug Report:

Reliance on default encoding Found reliance on default encoding: new java.io.FileWriter(File, boolean)

In which line i'm getting this Error?

  writer = new FileWriter(gpxfile, true);

Could some one please brief me what is this exactly? And how can we solve this?

like image 222
kavie Avatar asked Jul 13 '18 07:07

kavie


People also ask

What is Java IO FileWriter?

java.io.FileWriter. Writes text to character files using a default buffer size. Encoding from characters to bytes uses either a specified charset or the platform's default charset. Whether or not a file is available or may be created depends upon the underlying platform.

How do I change the encoding of a file in Java?

setProperty("file. encoding", "UTF-8"); byte inbytes[] = new byte[1024]; FileInputStream fis = new FileInputStream("response. txt"); fis. read(inbytes); FileOutputStream fos = new FileOutputStream("response-2.

What is the default encoding for output stream writer utf8?

StreamWriter(Stream) Initializes a new instance of the StreamWriter class for the specified stream by using UTF-8 encoding and the default buffer size.

What is Dm_default_encoding?

DM_DEFAULT_ENCODING: Reliance on default encoding 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.


1 Answers

Resolved this Issue by replacing

FileWriter writer = new FileWriter(gpxfile, true);

with

  FileOutputStream fileStream = new FileOutputStream(gpxfile);
            writer = new OutputStreamWriter(fileStream, "UTF-8");
like image 60
kavie Avatar answered Oct 10 '22 03:10

kavie