In this example we will show how to filter files with certain extensions. You can define methods to do this, as in example 1.You can also use the method list(FilenameFilter filter) in the File object to create an anonymous inner class to override the accept(File f,String name) method in the FilenameFilter interface , as in example 2.
Source Code
– Example (1)
package com.beginner.examples;
import java.io.File;
public class FilterFileTest {
public static void main(String[] args) {
filterFile(new File("Test"), "txt");
System.out.println("----------");
filterFile(new File("Test"), "java");
}
/**
*
* @param folder The folder you want to filter
* @param suff Suffix name of the file you want to filter
*/
public static void filterFile(File folder,String suff) {
if(!folder.isDirectory()) {
System.out.println("This is not a folder!");
return;
}
//Get all the files in this folder
File[] files = folder.listFiles();
for(int i = 0; i < files.length; i++ ) {
//Get the name of the file
String fileName = files[i].getName();
//Skip if it is not the suffix name specified
if(!fileName.toLowerCase().endsWith(suff)) {
continue;
}
System.out.println(fileName);
}
}
}
Output:
test1.txt
test2.txt
test3.txt
----------
Test4.java
Test5.java
Test6.java
– Example (2)
package com.beginner.examples;
import java.io.File;
public class FilterFileTest_2 {
public static void main(String[] args) {
String[] fileNames = filterFile(new File("Test"), "txt");
if(fileNames!=null) {
for(String name : fileNames) {
System.out.println(name);
}
}
}
public static String[] filterFile(File folder ,String suff) {
if(!folder.isDirectory()) {
return null;
}
//use Lambda expressions
return folder.list((dir,name)->name.toLowerCase().endsWith(suff)?true:false);
//anonymous inner class writing
// return folder.list(
// new FilenameFilter() {
//
// @Override
// public boolean accept(File dir, String name) {
// if(name.toLowerCase().endsWith(suff)){
// return true;
// }else{
// return false;
// }
// }
// });
}
}
Output:
test1.txt
test2.txt
test3.txt
References
Imported packages in Java documentation: