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???
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.
use a finally block:
File f;
try {
f = ....
.. use f ...
} /* optional catches */
finally {
if (f != null) f.close();
}
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();
}
}
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) {
...
}
}
}
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);
}
}
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);
}