package fcm; import java.io.BufferedReader; import java.io.Reader; import java.io.FileReader; import java.io.File; import java.io.IOException; public class IOClosureTest { public interface ReaderCallback { public void doWithReader(Reader reader) throws IOException; } public static void doWithFile(File file, ReaderCallback callback) throws IOException { Reader reader = null; boolean done = false; try { reader = new FileReader(file); callback.doWithReader(reader); done = true; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { if (done) throw e; } } } } public interface LineCallback { public void doForLine(String line) throws IOException; } public static void forEachLine(File file, final LineCallback lineCallback) throws IOException { doWithFile(file, #(Reader reader) { BufferedReader bufferedReader = new BufferedReader(reader); String line; while ( (line = bufferedReader.readLine()) != null) { lineCallback.doForLine(line); } }); } public static void main(String[] args) throws IOException { forEachLine(new File(args[0]), #(String line) { System.out.println("This is a line:" + line); }); } public static void theOldWay(String[] args) throws IOException { BufferedReader reader = null; boolean done = false; try { reader = new BufferedReader(new FileReader(new File(args[0]))); String line; while ( (line = reader.readLine()) != null) { System.out.println("This is a line:" + line); } done = true; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { if (done) throw e; } } } } }