11

I have a directory, and inside it are files are named "a_id_XXX.zip".

How do check if a file exists given an id and File dir?

Bohemian
  • 412,405
  • 93
  • 575
  • 722
DrXCheng
  • 3,992
  • 11
  • 49
  • 72

7 Answers7

20

Pass a FileFilter (coded here anonymously) into the listFiles() method of the dir File, like this:

File dir = new File("some/path/to/dir");
final String id = "XXX"; // needs to be final so the anonymous class can use it
File[] matchingFiles = dir.listFiles(new FileFilter() {
    public boolean accept(File pathname) {
        return pathname.getName().equals("a_id_" + id + ".zip");
    }
});


Bundled as a method, it would look like:

public static File[] findFilesForId(File dir, final String id) {
    return dir.listFiles(new FileFilter() {
        public boolean accept(File pathname) {
            return pathname.getName().equals("a_id_" + id + ".zip");
        }
    });
}

and which you could call like:

File[] matchingFiles = findFilesForId(new File("some/path/to/dir"), "XXX");

or to simply check for existence,

boolean exists = findFilesForId(new File("some/path/to/dir"), "XXX").length > 0
Bohemian
  • 412,405
  • 93
  • 575
  • 722
6

i created zip files named with a_id_123.zip ,a_id_124.zip ,a_id_125.zip ,a_id_126.zip and it looks like working fine but i'm not sure if it's proper answer for you. Output will be the following if files listed above exists

  • found a_id_123.zip
  • found a_id_124.zip
  • found a_id_125.zip
  • found a_id_126.zip

    public static void main(String[] args) {
    
        String pathToScan = ".";
        String fileThatYouWantToFilter;
        File folderToScan = new File(pathToScan); // import -> import java.io.File;
        File[] listOfFiles = folderToScan.listFiles();
    
        for (int i = 0; i < listOfFiles.length; i++) {
    
            if (listOfFiles[i].isFile()) {
                fileThatYouWantToFilter = listOfFiles[i].getName();
                if (fileThatYouWantToFilter.startsWith("a_id_")
                        && fileThatYouWantToFilter.endsWith(".zip")) {
                    System.out.println("found" + " " + fileThatYouWantToFilter);
                }
            }
        }
    }
    
GiantRobot
  • 432
  • 3
  • 6
5

This solution generalizes on Bohemian's answer. It uses regular expressions and also replaces the inner class with Java 8 lambda expressions. Thanks @Bohemian for the original implementation.

import java.io.File;

public class FileFinder {
    public static void main(String[] args){
        File directory = new File("D:\\tmp");
        String id = "20140430104033";
        for (File f : findFilenamesWithId(id, directory)){
            System.out.println(f.getAbsoluteFile());
        }
    }

    /** Finds files in the specified directory whose names are formatted 
        as "a_id_ID.zip" */
    public static File[] findFilenamesWithId(String ID, File dir) {
        return findFilenamesMatchingRegex("^a_id_" + ID + "\\.zip$", dir);
    }

    /** Finds files in the specified directory whose names match regex */
    public static File[] findFilenamesMatchingRegex(String regex, File dir) {
        return dir.listFiles(file -> file.getName().matches(regex));
    }
}
Yeison
  • 193
  • 3
  • 6
2

Java 7 has some good support for pattern matching (PathMatcher) and recursive directory walking (Files.walkFileTree()). In the context of the original question, this page in Oracle's Java documentation is a good start:

Finding Files: http://docs.oracle.com/javase/tutorial/essential/io/find.html

Dave Hartnoll
  • 1,144
  • 11
  • 21
1

You can use apache WildCardFileFilter

https://commons.apache.org/proper/commons-io/javadocs/api-1.4/org/apache/commons/io/filefilter/WildcardFileFilter.html

nkare
  • 397
  • 6
  • 17
0

Using Java 8 find all files in directory and sub directory with required regex condition

My condition is to find all files with Audit_Report_xxxxxx.xls

// get List of Audit Report file in directory and sub directory
public List<String> getAuditReporFile(String baseDirectory) throws Exception{

    // select all available files in directory and subdirectory
    return Files.walk(Paths.get(baseDirectory))
            .filter(Files::isRegularFile).filter(x-> {

                // use regex and check if file name is according to our requirement
                return Pattern.compile("Audit_Report_.*\\.xls").matcher(x.getFileName().toString()).find();

            }).map(x->x.getFileName().toString()).collect(Collectors.toList());
}
rohit prakash
  • 565
  • 6
  • 12
0

The other answers or try the ant libraries. Here's an example: http://code.google.com/p/maven-replacer-plugin/source/browse/trunk/src/main/java/com/google/code/maven_replacer_plugin/include/FileSelector.java

Steven
  • 3,844
  • 3
  • 32
  • 53