java - How do I open, write and save a file while avoiding errors? -


i need erase file in program. solution have erase() method so:

public static void erase(string string) {     filewriter fw = null;     try {         fw  = new filewriter(string);         fw.write(new string());     } catch (ioexception ie) {         e.printstacktrace();     } {         fw.flush();         fw.close();      } } 

several problems here:

  • if fw not initialize (for whatever reason, missing file, invalid persmissions, etc) when try close in finally block, there nullpointerexception.

  • if don't have block, might throwing nullpointerexception reason above.

  • if close file inside try block, might leak resource if file opens, doesn't write.

what other problems overlooking , how can harden method?

you can wrap functionality in if-statement:

if(fw != null){     fw.close();  } 

this ensure if file ever opened, closed. if wasn't opened in first place, won't anything, want.

also, i'm not sure if it's posting, it's not advisable print stacktrace in catch block , continue ("swallowing" exception). should let exception thrown because hide bugs , make tracking them down hard.

edit: see comment below.


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -