Skip to main content

Java IO File Reader Question

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
No replies
liamshannon
Offline
Joined: 2011-07-12

Hey just wondering if anyone could help with out the a few hints or tips in relation to the following questions?

1. Please list your observations about this class, including bugs, poor programming, inefficiencies, etc...
2. Provide an alternate implementation that addresses your observations above, please call the method readFileFixed().

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();
}
}

Many Thanks in Advance