3

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:

OBL_UNSATISFIED_OBLIGATION: Method may fail to clean up stream or resource writeDataToFile(String) may fail to clean up java.io.Writer on checked exception

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?

kavie
  • 2,154
  • 4
  • 28
  • 53

1 Answers1

2

You are getting this error because of writer.flush();. This could lead to IOException since it writes any buffered output to the underlying stream. If the exception occurs the writer won't be closed.

If its mandatory to flush in finally{..} then use dedicated try{..} catch{..} for each line as follows:

finally {
    if (writer != null) {
        try {
            writer.flush();                
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Sagar
  • 23,903
  • 4
  • 62
  • 62
  • Thank u:-),That issue is gone ,But in same line I got one more findbugs Warning Says "Found reliance on default encoding: new java.io.FileWriter(File, boolean)" . Can u help me for this? – kavie Jul 13 '18 at 06:43
  • @kavie you can check out this [SO](https://stackoverflow.com/questions/10347435/found-reliance-on-default-encoding) for that – Sagar Jul 13 '18 at 06:44
  • If I use String I can use some Default encoding methods,But here I'm passing File as first parameter right? – kavie Jul 13 '18 at 06:57
  • @kavie looks like its pointing to fact that simply using append will use default encoding. There is a way to change the encoding as shown in this [SO](https://stackoverflow.com/questions/35132693/set-encoding-as-utf-8-for-a-filewriter). However you might need to do some extra work. I would recommend you to create new question for it if the link doesn't help. – Sagar Jul 13 '18 at 07:06