|
Get the content of a directory with a Filter |
|
|
First you create a class that implements java.io.FilenameFilter and then code the accept()
method, then call File.list() with the filter as a parameter. The returned array of strings has all
the names that passed through the accept()filter.
import java.io.File;
import java.io.FilenameFilter;
public class Filter implements FilenameFilter {
protected String pattern;
public Filter (String str) {
pattern = str;
}
public boolean accept (File dir, String name) {
return name.toLowerCase().endsWith(pattern.toLowerCase());
}
public static void main (String args[]) {
if (args.length != 1) {
System.err.println ("usage: java Filter ex. java Filter java");
return;
}
Filter nf = new Filter (args[0]);
// current directory
File dir = new File (".");
String[] strs = dir.list(nf);
for (int i = 0; i < strs.length; i++) {
System.out.println (strs[i]);
}
}
}
|
Here a version to support multiple filters.
import java.io.File;
import java.io.FilenameFilter;
import java.util.*;
import java.util.TreeSet.*;
public class Filter2 implements FilenameFilter {
protected Set extensionsSet;
public Filter2 (String [] extensions) {
extensionsSet = new TreeSet();
for (Iterator ext=Arrays.asList(extensions).iterator(); ext.hasNext();) {
extensionsSet.add(ext.next().toString().toLowerCase().trim());
}
extensionsSet.remove("");
}
public boolean accept (File dir, String name) {
final Iterator exts = extensionsSet.iterator();
while (exts.hasNext()) {
if (name.toLowerCase().endsWith(exts.next().toString())) {
return true;
}
}
return false;
}
public static void main (String args[]) {
if (args.length < 1) {
System.err.println ("usage: java Filter ex. java Filter java txt");
return;
}
Filter2 nf = new Filter2 (args);
// current directory
File dir = new File (".");
String[] strs = dir.list(nf);
for (int i = 0; i < strs.length; i++) {
System.out.println (strs[i]);
}
}
}
|
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.