Find files in a folder using Java

前端 未结 12 1915
日久生厌
日久生厌 2020-11-28 08:15

What I need to do if Search a folder say C:\\example

I then need to go through each file and check to see if it matches a few start characters so if fil

相关标签:
12条回答
  • 2020-11-28 08:30

    You can use a FilenameFilter, like so:

    File dir = new File(directory);
    
    File[] matches = dir.listFiles(new FilenameFilter()
    {
      public boolean accept(File dir, String name)
      {
         return name.startsWith("temp") && name.endsWith(".txt");
      }
    });
    
    0 讨论(0)
  • 2020-11-28 08:36

    I know, this is an old question. But just for the sake of completeness, the lambda version.

    File dir = new File(directory);
    File[] files = dir.listFiles((dir1, name) -> name.startsWith("temp") && name.endsWith(".txt"));
    
    0 讨论(0)
  • 2020-11-28 08:37

    Consider Apache Commons IO, it has a class called FileUtils that has a listFiles method that might be very useful in your case.

    0 讨论(0)
  • 2020-11-28 08:39

    What you want is File.listFiles(FileNameFilter filter).

    That will give you a list of the files in the directory you want that match a certain filter.

    The code will look similar to:

    // your directory
    File f = new File("C:\\example");
    File[] matchingFiles = f.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.startsWith("temp") && name.endsWith("txt");
        }
    });
    
    0 讨论(0)
  • 2020-11-28 08:40

    Appache commons IO various

    FilenameUtils.wildcardMatch

    See Apache javadoc here. It matches the wildcard with the filename. So you can use this method for your comparisons.

    0 讨论(0)
  • 2020-11-28 08:41

    As of Java 1.8, you can use Files.list to get a stream:

    Path findFile(Path targetDir, String fileName) throws IOException {
        return Files.list(targetDir).filter( (p) -> {
            if (Files.isRegularFile(p)) {
                return p.getFileName().toString().equals(fileName);
            } else {
                return false;
            }
        }).findFirst().orElse(null);
    }
    
    0 讨论(0)
提交回复
热议问题