Top / Java Closure
Ruby言語のようなブロック構文を記述できる
http://d.hatena.ne.jp/t_yano/20061004/1159987463
public interface Closure <T> { public void execute(T input); }
package codetest; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.net.URI; import java.util.logging.Logger; import org.apache.commons.collections15.Closure; public class IterableFile extends File { public IterableFile(File parent, String child) { super( parent, child); } public IterableFile(String pathname) { super( pathname); } public IterableFile(String parent, String child) { super( parent, child); } public IterableFile(URI uri) { super( uri); } public void eachLine( Closure<String> proc) throws FileNotFoundException, IOException { BufferedReader reader = null; try { reader = new BufferedReader( new FileReader( this)); String line = reader.readLine(); while( line != null) { proc.execute( line); line = reader.readLine(); } } catch( BreakException ex) { return; } finally { if( reader != null) { try { reader.close(); Logger.global.info( "**** File has been closed."); } catch (IOException ex) {} //close quietly. } } } }
package codetest; import org.apache.commons.collections15.Closure; public class IteratorTest { public static void main( String[] args) throws Exception { //ファイルを作って IterableFile inputFile = new IterableFile("/Users/ben/ListProp.java"); //一行ずつ処理する inputFile.eachLine( new Closure<String>() { public void execute(String line) { System.out.println(line); if( line.startsWith("p")) throw new BreakException(); } }); //ここではもう閉じられている。 } }