tags:

views:

79

answers:

6

just think that when I opened my file then when I want to write something in it ,one Exception will be thrown,and if I used file.close() in the try block ,So because of that Exception will not work, where should I close my file???

+1  A: 

You should use a finally block. However close method can also throw an IOException, so you should surround it in a try-catch block too.

This link may be helpful.

kgiannakakis
That close throws an IOException is a bad design decision in my opinion.
butterchicken
A: 

use a finally block:

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

I use two try catch blocks.

One where I open the file + a bool to let me know that the file was opened successfully. The second one where I write something (after checking the bool if open was a success).

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

    }

    try
    {
    //check bool
    If(bSuccess)
    {
    //Do write operation
    }
    }
    catch
    {
    }
    finally
    {
      if(bSuccess)
     {
       File.close();
     }
    }
Ganesh R.
I like mfx's suggestion.
Ganesh R.
+5  A: 

The proper way to do so is:

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

The answer of David Rabinowitz is right, but it can get simpler with the use of Apache Commons IO. For the complicated try-block in the finally-clause it has a method, for closing any Stream without an exception. With this you can write this:

FileOutputStream out = null;
try {
  out = ...
  ...
  out.write(...);
  ...
  out.flush();
} catch (IOException ioe) {
  ...
} finally {
  if(out!=null) {
    org.apache.commons.io.IOUtils.closeQuietly(out);
  }
}
Mnementh
Why the downvote?
Mnementh
I wasn't aware of this method in IOUtils, thanks!
David Rabinowitz
+2  A: 

The general pattern for resources is acquire; try { use; } finally { release; }. If you try to rearrange that you'll often end up in a situation where you, say, release a lock without acquiring it. Note, in general there is no need to clutter with a null check. If you need to catch an exception from it all, surround all the code with a try-catch. So

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