readLine - 自分用のu.Utilsの実装 2010/09/11

Java用です。自分用のu.Utilsの実装です。
ファイルを読み込むコードを毎回書くのは結構苦痛だったりしてます。
巨大なファイルを想定して一気に読んで一気に吐き出すというふうにしてません。
ファイルを一行づつ読んで処理するためのユーティリティメソッドです。
どこからでも利用できるように、svnにあげときます。



EclipseとJavaがあれば、とりあえずどんなプラットフォーム(Windows,osx,Linux)でもなんとなくやっていけるなーとよく思います。

で、コード
実装はお手軽BufferedReaderのreadLineを使ってます。
package u;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public abstract class Utils {

public interface IExecutor {
public void pre();
public void exec(String line);
public void post();
}

abstract static public class AbstractExcutor implements IExecutor{
public void pre(){}
public void exec(String line){}
public void post(){}
}
/**
* implement
* use BufferedReader
*
* @param file
* @param executor
* @return
* @throws IOException
*/
public static IExecutor readLine(File file, IExecutor executor)
throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));

try {
executor.pre();
String line = null;
while ((line = reader.readLine()) != null) {
executor.exec(line);
}

} finally {
try {
reader.close();
} finally {
executor.post();
}

}

return executor;
}
}



使い方
package u;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

public class UsageUtils {

public static void main(String[] args) throws IOException,
URISyntaxException {
readLine();
}

static void readLine() throws IOException, URISyntaxException {
/*
* 1.
*/
Utils.readLine(
new File(UsageUtils.class.getResource(
"doc-files/日本語/日本語TEST_SJIS.txt").toURI()),
new Utils.IExecutor() {
int total = 0;

public void pre() {
System.out.println("*** pre");
}

public void post() {
System.out.println("*** post total[" + total + "]");
}

public void exec(String line) {
total++;
System.out.println("[" + line + "]");
}
});

/*
* 2.
*/
Utils.readLine(
new File(UsageUtils.class.getResource("doc-files/TEST.txt")
.toURI()), new Utils.AbstractExcutor(){
int total = 0;
public void exec(String line) {
total++;
System.out.println("[" + line + "]");
}
});

}
}

: