Fileクラスでフォルダ内のファイル一覧が取得できますが、
そこにファイル名や拡張子でフィルタリングをしたいときがあります。
if文を使っている方…もっと良い方法があります。
FilenameFilterを使う方がスマートです。
使い方はJavadocでも読んでください。
まあインターフェースを継承して実装する必要があるので、
普通はApache Commons IOのファイルフィルタを使うでしょう。
では一から実装する場合はどうするのがスマートなのか?
ひとつの解答がこちらです。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.io.FilenameFilter; | |
/** | |
* File.list()、File.listFiles()の正規表現フィルタリングを提供します. | |
* 大抵のフィルタリングは、これでどうにかなります. | |
* @author Bladean Mericle | |
*/ | |
public class RegularExpressionFilter implements FilenameFilter { | |
/** 正規表現の文字列. */ | |
private String regexField = null; | |
/** | |
* 正規表現の文字列を設定するコンストラクタです. | |
* @param regex 正規表現の文字列 | |
*/ | |
public RegularExpressionFilter(final String regex) { | |
regexField = regex; | |
} | |
/** | |
* 判定条件の処理を記述しています. | |
* @param dir ディレクトリ | |
* @param name ファイル名 | |
* @return 正規表現に一致した場合は真 | |
*/ | |
public final boolean accept(final File dir, final String name) { | |
return name.matches(regexField); | |
} | |
} |
つまり正規表現で何とかするわけです。
ファイル名でのフィルタリングなら、
ほぼこれひとつでどうとでもなることでしょう。
正規表現の書き方?
Javadocを…というかまずはそれを読め!
追記:ああ、Apache Commons IOにも正規表現フィルタはあるんで、
興味本位以外ではそっちを使ってくださいね。
0 件のコメント:
コメントを投稿