0

I just wondered if my object of FileOutputStream; out.close(); should be called in the catch block? Because the out object is still "open" in case of something happends.

If not, should anything else with the FileOutputStream object be handled in the catch block?

  public void saveBitmap(){

    final File myDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), folderName);
    myDir.mkdirs();
    final File file = new File(myDir, getFileName() + getFileExtension());
    FileOutputStream out = null;

    try {

        out = new FileOutputStream(file);
        viewToBitmap().compress(Bitmap.CompressFormat.JPEG, quality, out);

        }

        out.flush();
        out.getFD().sync();
        out.close();

    } catch (IOException e) {

        //should I out.close(); here too?

        e.printStackTrace();
        onBitmapSavedListener(false, null);
    }
  }

1 Answers1

2

You should close the connection in a finally block. So you can be sure it'll close on end of class.

  • But what if an error happends and we then go to the catch block? Should the connection be closed there too and be flushed? –  Jan 12 '17 at 20:00
  • 1
    Finally block will always be executed. This way if has occured an error or not the connection will be closed. – Jonatas Pereira Jan 13 '17 at 19:38