I have this class that implements FilenameFilter
package Logic;
import java.io.File;
import java.io.FilenameFilter;
public class Filter implements FilenameFilter {
String name;
public Filter(String name) {
this.name = name;
}
@Override
public boolean accept(File dir, String filename) {
return name.contains("bluetooth");
}
}
I use this class in this method:
public String searchForBluetoothFolder() {
String folderNameToSearchFor = "bluetooth";
File root = sdCard;
FilenameFilter filter = new Filter(folderNameToSearchFor);
String[] bluetoothFolder = root.list(filter);
for(int i = 0; i < bluetoothFolder.length; i++) {
Log.i("Bluetooth: ", bluetoothFolder[i]);
}
return "";
}
Inside the for-loop, the ouput is just all of the files in the root directory, not those who have bluetooth as name. What am I doing wrong here?
This is because you are checking whether
namecontains “bluetooth” and not whether thefileNamecontains the word “bluetooth”return name.contains("bluetooth");should be changed toreturn filename.contains("bluetooth");However, by the way you’re trying to implement, change it to
return filename.contains(name);so that you do actually check whether yourfileNamecontains thenamethat you’ve specified.Also keep in mind that “bluetooth” might not be evaluated the same with
contains()as “Bluetooth” or “blueTooth”. If you want case-insensitive search, then I would suggest tostandardizeyour name. Setnameto lowercase and check usingfilename.toLowerCase().contains(name.toLowerCase()). Something like: