[[JAVAの記事一覧]] &topicpath; *目次 [#d03cbefc] #contents *概要 [#dff96915] Ruby言語のようなブロック構文を記述できる *Closureインターフェース [#u58630ff] **参考URL [#d8e909f0] http://d.hatena.ne.jp/t_yano/20061004/1159987463 ***特徴 [#xfe06d7f] -Apache Jakarta Commonsの Collectionsに含まれる ***コード [#l07d26ee] public interface Closure <T> { public void execute(T input); } *eachLineを実装したFileクラスの拡張 [#e1e2e50a] -参考:http://d.hatena.ne.jp/t_yano/20061004/1159987463 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. } } } } *実行コード例 [#l6902cdc] 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(); } }); //ここではもう閉じられている。 } }