java - Right place to flush the object -
i have written small piece of code printing:
bufferedwriter out = null; try { out = new bufferedwriter(new outputstreamwriter( new fileoutputstream(filedescriptor.out), "ascii"), 512); out.write(msg + '\n'); out.flush(); } catch (unsupportedencodingexception e) { throw new illegalstateexception( "test failed ", e); } catch (ioexception e) { throw new illegalstateexception( "test failed", e); } { if (out != null) { out = null; } }
flushing of obj done in try block only. way or should flush object in block?
use modern syntax if can , don't worry that. closing automatically flush it, use try-with-resources syntax. code shorter , more readable:
try(bufferedwriter out = new bufferedwriter(new outputstreamwriter( new fileoutputstream(filedescriptor.out), "ascii"), 512)) { out.write(msg + '\n'); } catch (unsupportedencodingexception | ioexception e) { logger.info("test failed due exception."); throw new illegalstateexception("test failed", e); }
see more try-with-resources if unfamiliar syntax.
Comments
Post a Comment