简体   繁体   中英

Java, search files of given pattern and get the directory names and complete filenames

I am new to Java. Looking for code to search for files with .ofg extension in all the sub-directories of /var/data.

The desired outputs are

  • the subdirectory name(s), which has the files with those files
  • the full names of the files
  • the number of those files in that subdirectory.

There are some tutorials available, but nothing i could find fitting to my code base; like

public class FindFiles {

    int inProcThreshold = 0;

    protected File recurfile(File file) {
        File[] dirlist = file.listFiles();

        for (File f : dirlist) {
            if (f.isDirectory()) {
                return f;
            }
        }

        return null;
    }

    protected int numOfInProcs(String location, int level, int maxdepth) {
        File base = new File(location);
        File[] firstlevelfiles = base.listFiles();

        while (level <= maxdepth) {
            for (File afile : firstlevelfiles) {
                if (afile.isDirectory()) {
                    base = recurfile(afile);
                } else {
                    if (afile.getName().endsWith(".txt")) {
                        inProcThreshold++;
                    }
                }
            }
            level++;
        }

        return inProcThreshold;
    }

    public static void main(String[] args) {
        FindFiles test = new FindFiles();
        String dirToList = "I:\\TEST-FOLDER";
        String ext = ".txt";
        int count = test.numOfInProcs(dirToList, 0, 10);
        System.out.println("Number of txt files are " + count);
    }

}

This is the code I am trying but it returns 0 as output to me. I am trying to search for files with extension.txt in the I:\\TEST-FOLDER subfolders.

Use this filter by giving directory addres in dirName Parameter it will list all directories with extension .ofg

 import java.io.File;
import java.io.FilenameFilter;

public class Filter {

    public File[] finder( String dirName){
        File dir = new File(dirName);

        return dir.listFiles(new FilenameFilter() { 
                 public boolean accept(File dir, String filename)
                      { return filename.endsWith(".ofg"); }
        } );

    }

}

I think what you are looking for is Files.find . Pass it a Predicate which checks that path.toString().endsWith(".ofg"),

It will return a Stream of Path objects representing the matching files. You can extract all the data you want by iterating on this Stream.

If you are not required to write the recursive part yourself (for practice or as task), you could use Files#walkFileTree with a custom implementation of the FileVisitor Interface (As @ Mena proposed in his comment).

Extend the SimpleFileVisitor class (or implement the FileVisitor interface) and provide your code to be executed on each file:

public class OfgFolderCollectingFileVisitor extends SimpleFileVisitor<Path> {

  /** Stores the matching file paths */
  private final List<Path> collectedPaths = new LinkedList<>();


  @Override
  public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
    // check if the current file is an .ofg file
    if (file.toString().endsWith(".ofg")) {
      // it is -> add it's containing folder to the collection
      this.collectedPaths.add(file.getParent());
    }

    return super.visitFile(file, attrs);
  }


  public List<Path> getCollectedPaths() {
    return this.collectedPaths;
  }

}

Then pass an instance of your implementation to Files#walkFileTree and check the collected paths afterwards:

final OfgFolderCollectingFileVisitor visitor = new OfgFolderCollectingFileVisitor();

try {
  Files.walkFileTree(Paths.get("/var/data"), visitor);
} catch (final IOException ex) {
  ex.printStackTrace();
  return;
}

// let's see if something matched our criteria

final List<Path> ofgContainers = visitor.getCollectedPaths();

System.out.printf("Files found: %d%n", ofgContainers.size());

if (!ofgContainers.isEmpty()) {
  System.out.printf("%nContaining directories:%n");

  for (final Path ofgContainer : ofgContainers) {
    System.out.printf("- %s%n", ofgContaininer);
  }
}

Here is some example output (yes, folder2 and it's subfolder contain an .ofg file)

Files found: 3

Containing directories:
- \var\data\folder1\folder1.1
- \var\data\folder2
- \var\data\folder2\folder2.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM