Wednesday, 28 August 2013

How to delete a file on a method exit in java?

How to delete a file on a method exit in java?

I am trying to figure out how to make sure a temporary file that gets
created in a method gets deleted by the time the method returns. I have
tried file.deleteOnExit();, but that is for when the program stops, not
the method. I have also tried a try and finally block. Is using a finally
block the only way to achieve this?
public String example(File file) {
// do some random processing to the file here
file.canWrite();
InputStream() is = new FileInputStread(file);
// when we are ready to return, use the try finally block
try {
return file.getName();
} finally {
is.close();
file.delete();
}
}
I think it looks ugly. Anyone have a suggestion?

No comments:

Post a Comment