0

I've been strugling with a problem connected with FilenameFilter. I'd like to pass an object of my class implementing FilenameFilter into a method which recursively goes through files into a folder tree. A version of this method without FilenameFilter object passed as an argument works fine, but overloaded version doesn't. The problem is that it doesn't go recursively into a folder tree, though it should. Maybe a possible problem is related to arguments of the accept(File dir, String name); method, there are two arguments and I'm not pretty sure if and how I should pass values to them... I'll be very grateful for any help... ps. The method listfilesRecursive(FilenameFilter filter) works on an object of a class MyFile with one argument and thus one field path

public class MyFile {

String path;
public MyFile (String path) {
    this.path = path;
}

List <File> list = new ArrayList<File> ();
List <String> nameList = new ArrayList <String> ();

 public List <File> listFilesRecursive(FilenameFilter fFilter) {

        File f1 = new File(path);

        File [] files = f1.listFiles(fFilter);

        for (File fil : files) {

            if (fil.isFile()) {
            list.add(fil);
            nameList.add(fil.getName());
        } else if (fil.isDirectory()) {
            this.path = fil.toString();
            this.listFilesRecursive(fFilter);

            }
        }
        Collections.sort(nameList);
        return list;
 }

and below is the class implementing FilenameFilter:

class MyFilenameFilter implements FilenameFilter {

    String ext;
public MyFilenameFilter (String ext) {
    this.ext = ext;
}
@Override
    public boolean accept(File dir, String name) {
//      System.out.println(name + " <<<<<<<<<<");
        if(name.lastIndexOf('.')>0)
           {
              int lastIndex = name.lastIndexOf('.');
              String str = name.substring(lastIndex);

              if(str.equals(ext))
              {
                 return true;
              }
           }
           return false;
        }

}

And finally, will FilenameFilter a good choice if I'd like to implement a method going though folders selecting them and filtring them accoring to their names?

musztard2000
  • 127
  • 2
  • 14
  • http://stackoverflow.com/questions/2534632/list-all-files-from-a-directory-recursively-with-java – hmashlah Mar 11 '14 at 21:21
  • Thank u, but in my case my job is to implement a method using FilenameFilter object specifically and, though I know that there are simpler ways of doing the job, I have to use FilenameFilter class... Still, do You have any idea what is wrong? – musztard2000 Mar 11 '14 at 21:35
  • I think your problem is this line this.path = fil.toString(); Try passing this as parameter instead of having it as class memeber – hmashlah Mar 11 '14 at 21:41
  • All right but then I won't need any fields in these object and as a result i will be able to get rid of any objects, do I think right? And don't You think it would be strange if this method without FilenameFilter argument worked fine and the one with an argument didn't? – musztard2000 Mar 11 '14 at 22:01
  • Thank You for Your kind help, however I've just solved the probblem which in fact wasn't the one you pointed. :) the method made an array of Files according to the fFilter which was a wrong idea, because if a main folder didn't contain the searched file the whole array (on which basically the method consisted of) was empty. so I removed an argument in the initial **listFiles()** method and I made the comparison later in the loop. :) Thank you for help anyway! – musztard2000 Mar 11 '14 at 22:18
  • Add file.isDirectory() check in accept method. See accepted answer [Link](http://stackoverflow.com/questions/12656569/recursive-method-to-search-through-folder-tree-and-find-specific-file-types). – Rajesh Oct 11 '16 at 22:59
  • Does this answer your question? [Recursive method to search through folder tree and find specific file types](https://stackoverflow.com/questions/12656569/recursive-method-to-search-through-folder-tree-and-find-specific-file-types) – LoukasPap Aug 24 '20 at 13:56

1 Answers1

0
package hasses.magical.xml.formatter;
import static hasses.magical.xml.formatter.UIOut.uiOut;

import java.io.FilenameFilter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class FormattingController
{
   private FilenameFilter fileFilter;

   public FormattingController(FormatParam settings)
   {
      super();
      this.settings = settings;
      //File filter  can of course be any old FileNameFilter implementation 
      fileFilter = new MagicFileNameFilter(settings);
   }

   private FormatParam settings;

   public Integer excecute()
   {
      //In this case dir is set from a placeholder but any old string will do
      try (Stream<Path> walk = Files.walk(Paths.get(settings.getDir()))) {
         //forEach can ofcourse be called path->formatFile(path, someOtherCoolParam) if needed 
         walk.filter(path->fileFilter.accept(null, path.toFile().getName())).forEach(this::formatFile);
         
      } catch (IOException e) {
         uiOut("IOException during traverse dir: %s please check this a valid directory",settings.getDir());
         return -99;
      }
      return 0;
   }

   private void formatFile(Path path)
   {
      if(settings.getVerbose()) {
         uiOut("Will attempt to format: %s",path);
      }
      //do formatting or whatever...
   }

}
  • 2
    Please add some comments or description and not just paste some code. – Tom-Oliver Heidel Sep 25 '20 at 13:07
  • Ok thought it was sort of self-explanatory. The class constructor creates FilenameFilter in my case a specific for my project. However, any FilenameFilter will do. method excecute walks recursively over the given directory (in my case from a given placeholder, but any old string pointing to a dir will do). The filename filter is used on each file in the "walk". for each file passing the filter, We invoke the formatFile method with the given path. – pinbalwizz Oct 08 '20 at 11:45
  • clarification: for each file passing the filename to the filter – pinbalwizz Oct 09 '20 at 07:00