Héctor
Héctor

Reputation: 26084

Should I close output stream if I get FileNotFoundException? And IOException?

I have this code:

   private void save(Bitmap bitmap) {
        try {
            FileOutputStream fos = new FileOutputStream(path);
            bitmap.compress(Bitmap.CompressFormat.JPEG, COMPRESSION_QUALITY, fos);
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Do I need to close the FileOutputStream in FileNotFoundException catch block?

If that exception is thrown means that file could not be opened so I think that it would not be necessary. However, I think it would be nice to do it in IOException catch block.

Could it cause any memory leak error or something similar if I don't do it?

Thanks.

Upvotes: 3

Views: 372

Answers (3)

user207421
user207421

Reputation: 310978

There is nothing to close. The FileOutputStream constructor threw an exception; the stream was never constructed; the fos variable has never been assigned; and it is out of scope in the catch block.

Upvotes: 1

OldCurmudgeon
OldCurmudgeon

Reputation: 65859

If you are working in Java 7 or above you should use a try with resources and let the system decide.

private void save(Bitmap bitmap) {
    try (FileOutputStream fos = new FileOutputStream(path)) {
        bitmap.compress(Bitmap.CompressFormat.JPEG, COMPRESSION_QUALITY, fos);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

If not then just ensure that the stream is not null first and do it in a finally.

private void save(Bitmap bitmap) {
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(path);
        bitmap.compress(Bitmap.CompressFormat.JPEG, COMPRESSION_QUALITY, fos);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (fos != null) {
            fos.close();
        }
    }
}

Upvotes: 1

Tommaso Pasini
Tommaso Pasini

Reputation: 1645

You should always close the file once you have finished to read or write. Otherwise you will keep the resource busy and in general could be a problem.
If you modify your code in this way you will not have to care about close the file and java will think about it.

    private void save(Bitmap bitmap) {
       try(FileOutputStream fos = new FileOutputStream(path)) {
          bitmap.compress(Bitmap.CompressFormat.JPEG, COMPRESSION_QUALITY, fos);
       } catch (FileNotFoundException e) {
          e.printStackTrace();
       } catch (IOException e) {
          e.printStackTrace();
       }
    }

Upvotes: 0

Related Questions