Skip to content

Instantly share code, notes, and snippets.

@hugo4715
Forked from tomoyamkung/ExtensionFileFilter.java
Created September 3, 2016 17:06
Show Gist options
  • Save hugo4715/8a6c3e9343f3b6e1cbf7b9985c765e07 to your computer and use it in GitHub Desktop.
Save hugo4715/8a6c3e9343f3b6e1cbf7b9985c765e07 to your computer and use it in GitHub Desktop.
[Java]FilenameFilter を使ったフィルタクラス。
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);
}
}
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