I’m writing a class that just reads a text file and prints out the lines. I’m getting an error on the line containing BufferedReader rd = new BufferedReader(new FileReader(“file.txt”)); saying that Syntax error on token “;”, { expected after this token. I’ve tried placing it within a method, and within a try catch block as it recommends but then I’m unable to resolve the rd variable. I’m using the acm package so some of the other syntax may look different but I receive no other errors. Any help would be greatly appreciated =)
import acm.program.*;
import acm.util.*;
import java.io.*;
import java.util.*;
public class FileReading extends ConsoleProgram {
BufferedReader rd = new BufferedReader(new FileReader("file.txt"));
try {
while (true) {
String line = rd.readLine();
if (line == null) {
break;
}
println(line);
}
rd.close();
}
catch (IOException ex) {
throw new ErrorException(ex);
}
}
}
Code blocks like this should be embodied inside a method or a static clause. Something like: