2

I have been stuck with this problem for a while, I have read some tutorials and documentations of how implement an inputStream variable and its life cycle, nevertheless I get over an over again the same error marked by "Infer" the static analyzer from facebook, It is suggesting me that there is a problem of: RESOURCE_LEAK in this code:

File file = new File(PATH_PROFILE + UserHelper.getInstance().getUser().getId() + ".jpg");
    OutputStream os = null;
    try {
        os = new FileOutputStream(file);
        os.write(dataBytes);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (os != null) {
            try {
                os.flush();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

The description error is:

error: RESOURCE_LEAK resource of type java.io.FileOutputStream acquired by call to FileOutputStream(...) at line 494 is not released after line 499.

But I release it in the finally block, this is a false error alarm? or I am missing something? because I have been in this for a while and i cant get where is the error.

I'am really thankfully for your help and support.

dicarlomagnus
  • 576
  • 4
  • 17

1 Answers1

4

Use try-with-resources (available since Java 7).

File file = new File(PATH_PROFILE + UserHelper.getInstance().getUser().getId() + ".jpg");
try (OutputStream os = new FileOutputStream(file)) {
    os.write(dataBytes);
} catch (Exception e) {
    e.printStackTrace();
}

To learn more, read:

Andreas
  • 154,647
  • 11
  • 152
  • 247