This question already has answers here:
Java try/catch/finally best practices while acquiring/closing resources
                                
                                    (8个答案)
                                
                        
                3年前关闭。
            
        

我只是想知道我的FileOutputStream对象是否; out.close();应该在catch块中调用吗?因为发生某些情况时,out对象仍处于“打开”状态。

如果不是,是否应该在catch块中处理FileOutputStream对象的其他内容?

  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);
    }
  }

最佳答案

您应该在finally块中关闭连接。因此,您可以确定它会在课程结束时关闭。

关于java - 应该FileOutputStream.close();在IOException的catch块中被调用? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41621758/

10-10 02:47