androidfindbugs

writeDataToFile(String) may fail to clean up java.io.Writer on checked exception in FindBugs


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?


Solution

  • 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 it's 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();
            }
        }
    }