Hi I was given this class and method and asked to:
" Please list your observations about this class, including bugs, poor programming, inefficiencies, etc..."
And wrote an alternative version using a Scanner instead and identified the forward slashes should be back slashes and escaped and provided my own readFileFixed() method, however I was told that this wasn't a very good solution and that I should go off and think a bit more about it, but cant really think of anything else and would be really greatful for any hints, tips or Advice....
package codeTest; import java.io.File; import java.io.FileReader; public class CodeTestExerciseBadCode { public CodeTestExerciseBadCode(){ } /** * @param args */ public static void main(String[] args) { CodeTestExerciseBadCode part2 = new CodeTestExerciseBadCode(); System.out.println(part2.readFile()); } public String readFile(){ File f = null; FileReader fr = null; StringBuffer content = null; try{ f = new File("c:/samplefile.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(); } }
And my solution
public String readFileFixed() { StringBuffer content; content = new StringBuffer(); File file = new File("C:\\here\\sampletextfile.txt"); try { Scanner scanner = new Scanner(file); while (scanner.hasNextLine()) { content.append(scanner.nextLine()); content.append(System.getProperty("line.separator")); } } catch (Exception e) { e.printStackTrace(); } return content.toString(); }
So any suggestions would be great, thanks...