【问题标题】:How do I scan a folder in Java?如何在 Java 中扫描文件夹?
【发布时间】:2010-03-04 19:45:10
【问题描述】:

我需要扫描 Java 中的特定文件夹,并且能够返回特定类型的文件的整数个数(不仅基于扩展名,还基于命名约定。)例如,我想知道有多少个 JPG 文件\src 文件夹中有一个简单的整数文件名(例如,1.JPG 到 30.JPG)。谁能指出我正确的方向?谢谢

【问题讨论】:

    标签: java directory


    【解决方案1】:

    java.io.File.list(FilenameFilter) 是您正在寻找的方法。

    【讨论】:

      【解决方案2】:

      我有一个使用正则表达式模式来处理相当复杂的文件结构的方法。可以使用类似的东西,尽管我确信它可以比我的示例更简洁(为了安全而编辑)。

      /**
           * Get all non-directory filenames from a given foo/flat directory
           * 
           * @param network
           * @param typeRegex
           * @param locationRegex
           * @return
           */
          public List<String> getFilteredFilenames(String network, String typeRegex, String locationRegex) {
      
              String regex = null;
      
              List<String> filenames = new ArrayList<String>();
              String directory;
      
              // Look at the something network
              if (network.equalsIgnoreCase("foo")) {
      
                  // Get the foo files first
                  directory = this.pathname + "/" + "foo/filtered/flat";
                  File[] foofiles = getFilenames(directory);
      
                  // run the regex if need be.
                  if (locationRegex != null && typeRegex != null ) {
                      regex = typeRegex + "." + locationRegex;
      
                      //System.out.println(regex);
                  }
      
      
                  for (int i = 0; i < foofiles.length; i++) {
                      if (foofiles[i].isFile()) {
                          String file = foofiles[i].getName();
      
                          if (regex == null) {
                              filenames.add(file);
                          }
                          else {
                              if (file.matches(regex)) {
                                  filenames.add(file);
                              }
                          }
                      }
                  }
              }
      
              return filenames;
          }
      

      【讨论】:

        猜你喜欢
        • 2010-09-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-25
        • 2012-03-16
        • 2021-07-23
        • 2013-06-14
        • 1970-01-01
        相关资源
        最近更新 更多