org.apache.commons.io.FileUtils.listFiles()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(11.8k)|赞(0)|评价(0)|浏览(429)

本文整理了Java中org.apache.commons.io.FileUtils.listFiles()方法的一些代码示例,展示了FileUtils.listFiles()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。FileUtils.listFiles()方法的具体详情如下:
包路径:org.apache.commons.io.FileUtils
类名称:FileUtils
方法名:listFiles

FileUtils.listFiles介绍

[英]Finds files within a given directory (and optionally its subdirectories). All files found are filtered by an IOFileFilter.

If your search should recurse into subdirectories you can pass in an IOFileFilter for directories. You don't need to bind a DirectoryFileFilter (via logical AND) to this filter. This method does that for you.

An example: If you want to search through all directories called "temp" you pass in FileFilterUtils.NameFileFilter("temp")

Another common usage of this method is find files in a directory tree but ignoring the directories generated CVS. You can simply pass in FileFilterUtils.makeCVSAware(null).
[中]查找给定目录(及其子目录)中的文件。找到的所有文件都由IOFileFilter筛选。
如果您的搜索应该递归到子目录中,您可以为目录传递IOFileFilter。您不需要将DirectoryFileFilter(通过逻辑AND)绑定到此筛选器。这个方法可以帮你做到这一点。
例如:如果要搜索所有名为“temp”的目录,请传入FileFilterUtils.NameFileFilter("temp")
此方法的另一个常见用法是在目录树中查找文件,但忽略CVS生成的目录。您只需传入FileFilterUtils.makeCVSAware(null)

代码示例

代码示例来源:origin: SonarSource/sonarqube

protected ExplodedPlugin explodeFromUnzippedDir(String pluginKey, File jarFile, File unzippedDir) {
  File libDir = new File(unzippedDir, PluginJarExploder.LIB_RELATIVE_PATH_IN_JAR);
  Collection<File> libs;
  if (libDir.isDirectory() && libDir.exists()) {
   libs = listFiles(libDir, null, false);
  } else {
   libs = Collections.emptyList();
  }
  return new ExplodedPlugin(pluginKey, jarFile, libs);
 }
}

代码示例来源:origin: apache/geode

Collection<File> getBackedUpOplogs(File checkedBaselineDir, DiskStore diskStore) {
 File baselineDir = new File(checkedBaselineDir, BackupWriter.DATA_STORES_DIRECTORY);
 baselineDir = new File(baselineDir, getBackupDirName((DiskStoreImpl) diskStore));
 return FileUtils.listFiles(baselineDir, new String[] {"krf", "drf", "crf"}, true);
}

代码示例来源:origin: gocd/gocd

private void cleanupTempFiles() {
  FileUtils.deleteQuietly(new File(FileUtil.TMP_PARENT_DIR));
  FileUtils.deleteQuietly(new File("exploded_agent_launcher_dependencies")); // launchers extracted from old versions
  FileUtils.listFiles(new File("."), AGENT_LAUNCHER_TMP_FILE_FILTER, FalseFileFilter.INSTANCE).forEach(FileUtils::deleteQuietly);
  FileUtils.deleteQuietly(new File(new SystemEnvironment().getConfigDir(), "trust.jks"));
}

代码示例来源:origin: gocd/gocd

private List<File> getAddonJarFiles() {
  File addonsPath = new File(systemEnvironment.get(SystemEnvironment.ADDONS_PATH));
  if (!addonsPath.exists() || !addonsPath.canRead()) {
    return new ArrayList<>();
  }
  return new ArrayList<>(FileUtils.listFiles(addonsPath, new SuffixFileFilter("jar", IOCase.INSENSITIVE), FalseFileFilter.INSTANCE));
}

代码示例来源:origin: gocd/gocd

public void initialize() throws IOException {
  if (!systemEnvironment.useCompressedJs()) {
    return;
  }
  String assetsDirPath = servletContext.getRealPath(servletContext.getInitParameter("rails.root") + "/public/assets/");
  File assetsDir = new File(assetsDirPath);
  if (!assetsDir.exists()) {
    throw new RuntimeException(String.format("Assets directory does not exist %s", assetsDirPath));
  }
  Collection files = FileUtils.listFiles(assetsDir, new RegexFileFilter(MANIFEST_FILE_PATTERN), null);
  if (files.isEmpty()) {
    throw new RuntimeException(String.format("Manifest json file was not found at %s", assetsDirPath));
  }
  File manifestFile = (File) files.iterator().next();
  LOG.info("Found rails assets manifest file named {} ", manifestFile.getName());
  String manifest = FileUtils.readFileToString(manifestFile, UTF_8);
  Gson gson = new Gson();
  railsAssetsManifest = gson.fromJson(manifest, RailsAssetsManifest.class);
  LOG.info("Successfully read rails assets manifest file located at {}", manifestFile.getAbsolutePath());
}

代码示例来源:origin: SonarSource/sonarqube

String driverPath(File homeDir, Provider provider) {
 String dirPath = provider.path;
 File dir = new File(homeDir, dirPath);
 if (!dir.exists()) {
  throw new MessageException("Directory does not exist: " + dirPath);
 }
 List<File> files = new ArrayList<>(FileUtils.listFiles(dir, new String[] {"jar"}, false));
 if (files.isEmpty()) {
  throw new MessageException("Directory does not contain JDBC driver: " + dirPath);
 }
 if (files.size() > 1) {
  throw new MessageException("Directory must contain only one JAR file: " + dirPath);
 }
 return files.get(0).getAbsolutePath();
}

代码示例来源:origin: SonarSource/sonarqube

@Override
public void start() {
 StringBuilder sb = new StringBuilder();
 batchDir = new File(fs.getHomeDir(), "lib/scanner");
 if (batchDir.exists()) {
  Collection<File> files = FileUtils.listFiles(batchDir, HiddenFileFilter.VISIBLE, FileFilterUtils.directoryFileFilter());
  for (File file : files) {
   String filename = file.getName();
   if (StringUtils.endsWith(filename, ".jar")) {
    try (FileInputStream fis = new FileInputStream(file)) {
     sb.append(filename).append('|').append(DigestUtils.md5Hex(fis)).append(CharUtils.LF);
    } catch (IOException e) {
     throw new IllegalStateException("Fail to compute hash", e);
    }
   }
  }
 }
 this.index = sb.toString();
}

代码示例来源:origin: meituan/WMRouter

/**
 * 扫描由注解生成器生成到包 {@link Const#GEN_PKG_SERVICE} 里的初始化类
 */
private void scanDir(File dir, Set<String> initClasses) throws IOException {
  File packageDir = new File(dir, INIT_SERVICE_DIR);
  if (packageDir.exists() && packageDir.isDirectory()) {
    Collection<File> files = FileUtils.listFiles(packageDir,
        new SuffixFileFilter(SdkConstants.DOT_CLASS, IOCase.INSENSITIVE), TrueFileFilter.INSTANCE);
    for (File f : files) {
      String className = trimName(f.getAbsolutePath(), dir.getAbsolutePath().length() + 1)
          .replace(File.separatorChar, '.');
      initClasses.add(className);
      WMRouterLogger.info("    find ServiceInitClass: %s", className);
    }
  }
}

代码示例来源:origin: apache/nifi

final Collection<File> files = FileUtils.listFiles(new File(baseDir), null, isRecursive);
final List<String> result = new ArrayList<String>();

代码示例来源:origin: alibaba/jvm-sandbox

final File fileOfPath = new File(path);
if(fileOfPath.isDirectory()) {
  foundModuleJarFiles.addAll(FileUtils.listFiles(new File(path), new String[]{"jar"}, false));
} else {
  if(StringUtils.endsWithIgnoreCase(fileOfPath.getPath(), ".jar")) {

代码示例来源:origin: simpligility/android-maven-plugin

File sourceFile = new File( parsedSource );
final String destinationPath;
if ( parsedDestination.endsWith( "/" ) )
        .listFiles( sourceFile, null, true );
    for ( File file : filesList )

代码示例来源:origin: alibaba/jvm-sandbox

private void init(final CoreConfigure cfg,
         final ClassLoader sandboxClassLoader) {
  final File providerLibDir = new File(cfg.getProviderLibPath());
  if (!providerLibDir.exists()
      || !providerLibDir.canRead()) {
    logger.warn("loading provider-lib[{}] was failed, doest existed or access denied.", providerLibDir);
    return;
  }
  for (final File providerJarFile : FileUtils.listFiles(providerLibDir, new String[]{"jar"}, false)) {
    try {
      final ProviderClassLoader providerClassLoader = new ProviderClassLoader(providerJarFile, sandboxClassLoader);
      // load ModuleJarLoadingChain
      inject(moduleJarLoadingChains, ModuleJarLoadingChain.class, providerClassLoader, providerJarFile);
      // load ModuleLoadingChain
      inject(moduleLoadingChains, ModuleLoadingChain.class, providerClassLoader, providerJarFile);
      logger.info("loading provider-jar[{}] was success.", providerJarFile);
    } catch (IllegalAccessException cause) {
      logger.warn("loading provider-jar[{}] occur error, inject provider resource failed.", providerJarFile, cause);
    } catch (IOException ioe) {
      logger.warn("loading provider-jar[{}] occur error, ignore load this provider.", providerJarFile, ioe);
    }
  }
}

代码示例来源:origin: alibaba/jstorm

Collection<File> files = FileUtils.listFiles(new File(jstormClientContext.hadoopConfDir), new String[]{JOYConstants.XML}, true);
for (File file : files) {
  LOG.info("adding hadoop conf file to conf: " + file.getAbsolutePath());

代码示例来源:origin: Netflix/Priam

public void findAndMoveForgottenFiles(Instant snapshotInstant, File snapshotDir) {
  try {
    Collection<File> snapshotFiles =
        FileUtils.listFiles(snapshotDir, FileFilterUtils.fileFileFilter(), null);
    File columnfamilyDir = snapshotDir.getParentFile().getParentFile();
    Collection<File> columnfamilyFiles =
      File originalFile = new File(columnfamilyDir, file.getName());
      columnfamilyFiles.remove(originalFile);

代码示例来源:origin: alibaba/jstorm

Collection<File> sstFiles = FileUtils.listFiles(new File(batchCpPath), new String[] { ROCKSDB_DATA_FILE_EXT }, false);
for (File sstFile : sstFiles) {
  if (!lastCheckpointFiles.contains(sstFile.getName())) {
File cpFileList = new File(batchCpPath + "/" + SST_FILE_LIST);
FileUtils.writeLines(cpFileList, sstFileList);
Collection<File> allFiles = FileUtils.listFiles(new File(batchCpPath), null, false);
allFiles.removeAll(sstFiles);
Collection<File> nonSstFiles = allFiles;

代码示例来源:origin: apache/kylin

@Override
  public void hook() throws IOException {
    super.hook();
    Collection<File> files = FileUtils.listFiles(new File(LOCALMETA_TEMP_DATA), null, true);
    for (File file : files) {
      file.setLastModified(lastModified);
    }
  }
}

代码示例来源:origin: zalando/zalenium

private void cleanupFiles(boolean reset) throws IOException {
  File testCountFile = new File(getLocalVideosPath(), TEST_COUNT_FILE);
  File dashboardHtml = new File(getLocalVideosPath(), DASHBOARD_FILE);
  deleteIfExists(dashboardHtml);
  deleteIfExists(testCountFile);
  if (reset) {
    File logsFolder = new File(getLocalVideosPath(), LOGS_FOLDER_NAME);
    File testInformationFile = new File(getLocalVideosPath(), TEST_INFORMATION_FILE);
    File videosFolder = new File(getLocalVideosPath());
    String[] extensions = new String[] { "mp4", "mkv" };
    // Find all the unique directories that contain videos that are in the videos folder, but not the videos folder itself.
    // The point is to delete build directories
    Set<File> directoriesToDelete = FileUtils.listFiles(videosFolder, extensions, true).stream()
        .filter(file -> file.getAbsolutePath().startsWith(videosFolder.getAbsolutePath()) && !file.getParentFile().equals(videosFolder))
        .map(File::getParentFile)
        .collect(Collectors.toSet());
    directoriesToDelete.forEach(Dashboard::deleteIfExists);
    // Delete any other videos left over, that weren't in build directories.
    for (File file : FileUtils.listFiles(videosFolder, extensions, true)) {
      deleteIfExists(file);
    }
    deleteIfExists(logsFolder);
    deleteIfExists(testInformationFile);
  }
  setupDashboardFile(dashboardHtml);
}

代码示例来源:origin: square/spoon

private void handleFiles(DeviceResult.Builder result, File testFileDir) throws IOException {
 File[] classNameDirs = testFileDir.listFiles();
 if (classNameDirs != null) {
  logInfo("Found class name dirs: " + Arrays.toString(classNameDirs));
  for (File classNameDir : classNameDirs) {
   String className = classNameDir.getName();
   File destDir = new File(fileDir, className);
   FileUtils.copyDirectory(classNameDir, destDir);
   logInfo("Copied " + classNameDir + " to " + destDir);
   // Get a sorted list of all files from the device run.
   List<File> files = new ArrayList<>(
     FileUtils.listFiles(destDir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE));
   Collections.sort(files);
   // Iterate over each file and associate it with its
   // corresponding method result.
   for (File file : files) {
    String methodName = file.getParentFile().getName();
    DeviceTest testIdentifier = new DeviceTest(className, methodName);
    final DeviceTestResult.Builder resultBuilder =
      result.getMethodResultBuilder(testIdentifier);
    if (resultBuilder != null) {
     resultBuilder.addFile(file);
     logInfo("Added file as result: " + file + " for " + testIdentifier);
    } else {
     logError("Unable to find test for %s", testIdentifier);
    }
   }
  }
 }
}

代码示例来源:origin: apache/storm

@Test
public void testPrepare() throws Exception {
  HdfsState state = createHdfsState();
  Collection<File> files = FileUtils.listFiles(new File(TEST_OUT_DIR), null, false);
  File hdfsDataFile = Paths.get(TEST_OUT_DIR, FILE_NAME_PREFIX + "0").toFile();
  Assert.assertTrue(files.contains(hdfsDataFile));
}

代码示例来源:origin: apache/storm

@Test
public void testIndexFileCreation() throws Exception {
  HdfsState state = createHdfsState();
  state.beginCommit(1L);
  Collection<File> files = FileUtils.listFiles(new File(TEST_OUT_DIR), null, false);
  File hdfsIndexFile = Paths.get(TEST_OUT_DIR, INDEX_FILE_PREFIX + TEST_TOPOLOGY_NAME + ".0").toFile();
  Assert.assertTrue(files.contains(hdfsIndexFile));
}

相关文章

FileUtils类方法