Skip to main content

Posts

Showing posts with the label filereader

Filereader null declarations and appending best practice

I want to optimise my file reader function but am not sure if it is best practice to declare the nulls outside of the try loop. Also, is looping and appending chars to a Stringbuffer considered bad practice? I would like to use the exception handling here, but maybe it is better to use another structure? any advice most welcome, thanks. public String readFile(){ File f = null; FileReader fr = null; StringBuffer content = null; try{ f = new File("c:/test.txt"); fr = new FileReader(f); int c; while((c = fr.read()) != -1){ if(content == null){ content = new StringBuffer(); } content.append((char)c); } fr.close(); } catch (Exception e) { throw new RuntimeException("An error occured reading your file"); } return content.toString(); } }