-
-
Save hugo4715/8a6c3e9343f3b6e1cbf7b9985c765e07 to your computer and use it in GitHub Desktop.
[Java]FilenameFilter を使ったフィルタクラス。
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
package net.tomoyamkung; | |
import java.io.File; | |
import java.io.FilenameFilter; | |
/** | |
* 指定した拡張子と一致するファイルを取得するフィルタクラス。 | |
* | |
* @author tomoyamkung | |
* | |
*/ | |
public class ExtensionFileFilter implements FilenameFilter { | |
private String extension; | |
public ExtensionFileFilter(String extension) { | |
this.extension = extension; | |
} | |
@Override | |
public boolean accept(File dir, String name) { | |
File file = new File(name); | |
if(file == null || file.isDirectory()) { | |
return false; | |
} | |
return name.endsWith(extension); | |
} | |
} |
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
package net.tomoyamkung; | |
import static org.hamcrest.CoreMatchers.*; | |
import static org.junit.Assert.*; | |
import java.io.File; | |
import org.junit.Test; | |
public class ExtensionFileFilterTest { | |
@Test | |
public void 拡張子がtxtのファイル名を取得する() throws Exception { | |
// Setup | |
String extension = ".txt"; | |
ExtensionFileFilter filter = new ExtensionFileFilter(extension); | |
File dir = new File("testdata/file_filter_test"); | |
// Exercise | |
String[] list = dir.list(filter); | |
// Verify | |
assertThat(list.length, is(2)); | |
assertThat(list[0], is("hoge1.txt")); | |
assertThat(list[1], is("hoge2.txt")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment