JAVAの記事一覧

Top / Java Closure

目次

概要

Ruby言語のようなブロック構文を記述できる

Closureインターフェース

参考URL

http://d.hatena.ne.jp/t_yano/20061004/1159987463

特徴

コード

public interface Closure <T> {
   public void execute(T input);
}

eachLineを実装したFileクラスの拡張

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();
           }
       });
       //ここではもう閉じられている。
   }
}
トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2010-07-14 (水) 12:28:25 (5027d)