Can I use FileNameExtensionFilter to filter out a list of files?
If by practical you mean writeable in 5 lines in java yes it is. There is no cleaner alternatives when you want to filter a list (as opposed to languages with functional constructs like Scala and its filter method).
I personaly do not see how you could do it better, if your use case is really to filter out files with bad extensions I would do the same in Java.
If you are worried to use interfaces and classes from javax.swing
you should not, both these classes depend only on java.io
or java.util.Locale
(for setting file name to lowercase according to english locale), so they are as clean as the FilenameFilter
from java.io
. If your deal is really to filter according to case insensitive extension you should definitely go this way, the only alternative my eclipse sees is com.google.gwt.thirdparty.guava.common.io.PatternFilenameFilter
implementing java.io.FilenameFilter
, but then you have a new dependency and you write a Regex pattern which is far less readable and maintainable than your extensions. So I would stay with FileNameExtensionFilter
if this is really your use case.
FilenameFilter to show list files with certain extension and directories
You have many ways of doing this. In particular, a java.io.FileFilter
gives you more flexibility than a FilenameFilter
, allowing you to test for directories using isDirectory()
:
File[] listOfFiles = folder.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().endsWith(".txt")
|| pathname.isDirectory();
}
});
Is there any better way to do filefilter for many ext?
With Java 6 or above, this is a perfect case for a FileNameExtensionFilter
... except that it extends javax.swing.filechooser.FileFilter
instead of implementing java.io.FileFilter
.
But it is trivial to write a wrapper for it:
File[] files = rootDir.listFiles(new FileFilter() {
private final FileNameExtensionFilter filter =
new FileNameExtensionFilter("Compressed files",
"zip", "jar", "z", "gz", "tar", "bz2", "bz");
public boolean accept(File file) {
return filter.accept(file);
}
});
File. ListFiles with FileNameFilter returning null instead of list of files with matching file name
Since you are using recursion, you should pass the list (of files) as a parameter to method find
and not create a new list on each invocation. Hence the method find
does not need to return a value.
public static void find(String path, String fName, List<File> fileList) {
File dir = new File(path);
if (dir.isDirectory()) {
for (File aChild : dir.listFiles()) {
if (aChild.isDirectory()) {
find(aChild.getAbsolutePath(), fName, fileList);
}
else {
String name = aChild.getName();
if (name.startsWith(fName) && name.endsWith(".txt")) {
fileList.add(aChild);
}
}
}
}
else {
String name = aChild.getName();
if (name.startsWith(fName) && name.endsWith(".txt")) {
fileList.add(aChild);
}
}
}
If method parameter path
indicates a directory, then list the files in that directory. For each file in the directory, check whether the name of the file matches your search criteria and if it does then add it to the list. If it doesn't then check if it is itself a directory and if it is then recursively call method find
with the new directory.
Initially call method find
like so
List<File> list = new ArrayList<File>();
find("C:\\Salary\\", "601246", list);
Now list
should contain the list of relevant files. So the following line will print the contents of list
System.out.println(list);
How to get a file with exact extension from ArrayList of files
You can use a FilenameFilter
to filter the files. The name of the file is passed a a String, to prevent the creation of large amounts of File
objects when listing the files.
This class exists since JDK 1.0.
Single extension filter
Java 7 and lower example:
List<File> files = new ArrayList<File>(Arrays.asList(f.listFiles(
new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".ext");
}
}
)));
Java 8 example:
List<File> files = new ArrayList<File>(Arrays.asList(f.listFiles(
(File dir, String name) -> name.endsWith(".ext")
)));
Multiple extension filter
When filtering multiple extensions, it will become harder. We first store the allowed extensions in a Set<>, then use its contains() method to compare every entry.
Set<String> allowed = new HashSet<>();
allowed.add("txt");
allowed.add("exe");
allowed.add("sh");
Then we split on dot in the file filter and compare the last part:
List<File> files = new ArrayList<File>(Arrays.asList(f.listFiles(
new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
String[] split = name.split("\.");
if(split.length == 1)
return allowed.contains("");
return allowed.contains(split[split.length - 1]);
}
}
)));
Method references of listFiles
There are actually several interesting parts to this question:
Q: What is
isHidden
, and why is it a permissible argument to File.listFiles()?https://www.geeksforgeeks.org/file-ishidden-method-in-java-with-examples
The isHidden() function is a part of File class in Java . This
function determines whether the is a file or Directory denoted by the
abstract filename is Hidden or not.The function returns true if the
abstract file path is Hidden else return false.Q: What is the
File::isHidden
syntax?The "double colon" is a method reference. It's new with Java 8 and higher.
Q: So why is isHidden() an acceptable FileFilter parameter?
https://docs.oracle.com/javase/8/docs/api/java/io/FileFilter.html
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
File::isHidden
is a lambda expression that returns "true" or "false".
listFiles(FileFilter) instead of listFiles(FileNameFilter)
Looks like you've imported
javax.swing.filechooser.FileFilter
instead of
java.io.FileFilter
Probably occurred when selecting the import from the IDE
If the correct import is used, the code should not compile due to the existence of the getDescription
method which is only found in the former. The description is used for display purposes on JFileChooser
dialogs and doesnt apply here.
Related Topics
What to Learn for Making Java Web Applications in Java Ee 6
How to Use Jsp/Jstl to Generate Dynamic CSS/JavaScript Files
How to Parse Date from Gmt Timezone to Ist Timezone and Vice Versa in Android
How to Draw Circle by Canvas in Android
How to Check Wifi or 3G Network Is Available on Android Device
Android Studio Could Not Initialize Class Org.Codehaus.Groovy.Runtime.Invokerhelper
Clearing and Setting the Default Home Application
How to Initialize List<String> Object in Java
How to Set the Style of List View Cells Based on a Condition in Javafx
Preemptive Basic Auth with Httpurlconnection
Send Sms Until It Is Successful