如何以特殊条件关闭我的文件?

时间:2009-07-02 06:47:36

标签: java file

只是认为当我打开文件时,当我想在其中写入内容时,会抛出一个异常,如果我在try块中使用了file.close(),那么因为Exception将无效, 我应该在哪里关闭我的文件???

6 个答案:

答案 0 :(得分:5)

这样做的正确方法是:

FileOutputStream out = null;
try {
  out = ...
  ...
  out.write(...);
  ...
  out.flush();
} catch (IOException ioe) {
  ...
} finally {
  if(out!=null) {
    try {
      out.close();
    } catch (IOException ioe) {
      ...
    }
  }
}

答案 1 :(得分:2)

资源的一般模式是acquire; try { use; } finally { release; }。如果你试图重新排列,那么你经常会遇到这样一种情况:比如说你在没有获得锁定的情况下释放锁定。注意,通常不需要使用空检查混乱。如果您需要从中捕获异常,请使用try-catch包围所有代码。所以

try {
    final InputStream in = new FileInputStream(file);
    try {
        ...
    } finally {
        in.close();
    }
} catch (IOException exc) {
    throw new SomeException(exc);
}

答案 2 :(得分:1)

你应该使用finally块。但是close方法也可以抛出IOException,所以你也应该在try-catch块中包围它。

link可能会有所帮助。

答案 3 :(得分:0)

使用finally块:

File f;
try {
 f = ....
 .. use f ...
} /* optional catches */ 
finally {
 if (f != null) f.close();
}

答案 4 :(得分:0)

我使用了两个try catch块。

我打开文件的地方+一个bool让我知道该文件已成功打开。 第二个我写的东西(检查bool后如果打开成功)。

    Try
    {
      //Open file. If success.
       bSuccess = true.
    }
    catch
    {

    }

    try
    {
    //check bool
    If(bSuccess)
    {
    //Do write operation
    }
    }
    catch
    {
    }
    finally
    {
      if(bSuccess)
     {
       File.close();
     }
    }

答案 5 :(得分:0)

David Rabinowitz的答案是正确的,但使用Apache Commons IO可以更简单。对于finally子句中复杂的try-block,它有一个方法,用于关闭任何Stream而没有异常。有了这个,你可以这样写:

FileOutputStream out = null;
try {
  out = ...
  ...
  out.write(...);
  ...
  out.flush();
} catch (IOException ioe) {
  ...
} finally {
  if(out!=null) {
    org.apache.commons.io.IOUtils.closeQuietly(out);
  }
}