Setup
private URI sourceFileURI;
@Before
public void setUp() throws URISyntaxException {
sourceFileURI = this.getClass().getClassLoader().getResource("com/levelup/java/io").toURI();
}
Straight up Java
@Test
public void find_files_by_extension_java () {
File dir = new File(sourceFileURI);
File[] files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
logger.info(Arrays.toString(files));
assertTrue(files.length >= 4);
}
Output
[
/leveluplunch/levelup-java-examples/target/test-classes/com/levelup/java/io/copy-file.txt,
/leveluplunch/levelup-java-examples/target/test-classes/com/levelup/java/io/file-to-byte-array.txt,
/leveluplunch/levelup-java-examples/target/test-classes/com/levelup/java/io/inputstream-to-string.txt,
/leveluplunch/levelup-java-examples/target/test-classes/com/levelup/java/io/sample.txt
]
Google Guava
@Test
public void find_files_by_extension_guava () {
Pattern pattern = Pattern.compile("^.*.txt");
FilenameFilter filterByExtension = new PatternFilenameFilter(pattern);
File dir = new File(sourceFileURI);
File[] files = dir.listFiles(filterByExtension);
logger.info(Arrays.toString(files));
assertTrue(files.length >= 4);
}
Output
[
/leveluplunch/levelup-java-examples/target/test-classes/com/levelup/java/io/copy-file.txt,
/leveluplunch/levelup-java-examples/target/test-classes/com/levelup/java/io/file-to-byte-array.txt,
/leveluplunch/levelup-java-examples/target/test-classes/com/levelup/java/io/inputstream-to-string.txt,
/leveluplunch/levelup-java-examples/target/test-classes/com/levelup/java/io/sample.txt
]
Apache Commons
@Test
public void filter_files_by_extension () {
File dir = new File(sourceFileURI);
FileFilter fileFilter = new WildcardFileFilter("*.txt");
File[] files = dir.listFiles(fileFilter);
logger.info(Arrays.toString(files));
assertTrue(files.length >= 4);
}
Output
[
/leveluplunch/levelup-java-examples/target/test-classes/com/levelup/java/io/copy-file.txt,
/leveluplunch/levelup-java-examples/target/test-classes/com/levelup/java/io/file-to-byte-array.txt,
/leveluplunch/levelup-java-examples/target/test-classes/com/levelup/java/io/inputstream-to-string.txt,
/leveluplunch/levelup-java-examples/target/test-classes/com/levelup/java/io/sample.txt
]