How to delete a file on a method exit in java? -
i trying figure out how make sure temporary file gets created in method gets deleted time method returns. have tried file.deleteonexit();
, when program stops, not method. have tried try
, finally
block. using finally
block way achieve this?
public string example(file file) { // random processing file here file.canwrite(); inputstream() = new fileinputstread(file); // when ready return, use try block try { return file.getname(); } { is.close(); file.delete(); } }
i think looks ugly. have suggestion?
as mentioned @backslash in specific case can remove file before return:
file.delete(); return "file processed!";
however in common case if code inside try block can throw exception approach looks fine. can use aspect oriented programming (e.g. using aspectj) looks overkill in case.
you can improve code using nice new feature of java 7. each instance of closable
closed in end of try
block, e.g.:
try ( inputstream in = ... ) { // read input stream. } // that's it. not have close in. closed automatically since inputstream implements closable.
so, can create class autodeletablefile
wraps file
, implements closable
. close()
method should delete file. in code work yours:
try ( autodeletablefile file = new autodeletablefile("myfile.txt"); ) { // deal file } // nothing here. file deleted automatically since close() method deletes file.
Comments
Post a Comment