Java Code Examples for java.nio.file.Files#find()

The following examples show how to use java.nio.file.Files#find() .
Example 1
Project: lucene-solr   File: SolrCLI.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Deletes time-stamped old solr logs, if older than n days
 * @param daysToKeep number of days logs to keep before deleting
 * @return 0 on success
 * @throws Exception on failure
 */
public int removeOldSolrLogs(int daysToKeep) throws Exception {
  prepareLogsPath();
  if (logsPath.toFile().exists()) {
    try (Stream<Path> stream = Files.find(logsPath, 2, (f, a) -> a.isRegularFile()
        && Instant.now().minus(Period.ofDays(daysToKeep)).isAfter(a.lastModifiedTime().toInstant())
        && String.valueOf(f.getFileName()).startsWith("solr_log_"))) {
      List<Path> files = stream.collect(Collectors.toList());
      if (files.size() > 0) {
        out("Deleting "+files.size() + " solr_log_* files older than " + daysToKeep + " days.");
        for (Path p : files) {
          Files.delete(p);
        }
      }
    }
  }
  return 0;
}
 
Example 2
Project: bazel-tools   File: Main.java    License: Apache License 2.0 5 votes vote down vote up
@MustBeClosed
@Override
public Stream<Path> findFilesMatching(final Path directory, final String syntaxAndPattern)
    throws IOException {
  final PathMatcher matcher = directory.getFileSystem().getPathMatcher(syntaxAndPattern);
  return Files.find(
      directory, Integer.MAX_VALUE, (p, a) -> matcher.matches(p) && !a.isDirectory());
}
 
Example 3
Project: ariADDna   File: LocalStoreIndexingService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param dir   directory for search
 * @param match search pattern (* - eny string, ? - eny one symbol, [X,Y] - X or Y, [0-5] - range, {ABC, XYX} - ABC or XYZ)
 * @return collection of files
 * @throws IOException
 */
public List<Path> findFiles(Path dir, String match) throws IOException {
    ArrayList<Path> pathArrayList = new ArrayList<>();
    PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + match);
    try (Stream<Path> pathStream = Files.find(dir, Integer.MAX_VALUE,
            (path, basicFileAttributes) -> matcher.matches(path.getFileName()))) {
        pathArrayList.addAll(pathStream.collect(Collectors.toList()));
    }
    return pathArrayList;
}
 
Example 4
Project: dragonwell8_jdk   File: StreamTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testFind() throws IOException {
    PathBiPredicate pred = new PathBiPredicate((path, attrs) -> true);

    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        Set<Path> result = s.collect(Collectors.toCollection(TreeSet::new));
        assertEquals(pred.visited(), all);
        assertEquals(result.toArray(new Path[0]), pred.visited());
    }

    pred = new PathBiPredicate((path, attrs) -> attrs.isSymbolicLink());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> assertTrue(Files.isSymbolicLink(path)));
        assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) ->
        path.getFileName().toString().startsWith("e"));
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> assertEquals(path.getFileName().toString(), "empty"));
        assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) ->
        path.getFileName().toString().startsWith("l") && attrs.isRegularFile());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> fail("Expect empty stream"));
        assertEquals(pred.visited(), all);
    }
}
 
Example 5
Project: robozonky   File: FileUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static Either<Exception, Optional<File>> findFolder(final String folderName) {
    final Path root = new File(System.getProperty("user.dir")).toPath();
    try (var folders = Files.find(root, 1, (path, attr) -> attr.isDirectory())) {
        return Either.right(folders.map(Path::toFile)
            .filter(f -> Objects.equals(f.getName(), folderName))
            .findFirst());
    } catch (Exception ex) {
        LOGGER.warn("Exception while walking file tree.", ex);
        return Either.left(ex);
    }
}
 
Example 6
Project: jdk8u60   File: StreamTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testFind() throws IOException {
    PathBiPredicate pred = new PathBiPredicate((path, attrs) -> true);

    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        Set<Path> result = s.collect(Collectors.toCollection(TreeSet::new));
        assertEquals(pred.visited(), all);
        assertEquals(result.toArray(new Path[0]), pred.visited());
    }

    pred = new PathBiPredicate((path, attrs) -> attrs.isSymbolicLink());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> assertTrue(Files.isSymbolicLink(path)));
        assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) ->
        path.getFileName().toString().startsWith("e"));
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> assertEquals(path.getFileName().toString(), "empty"));
        assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) ->
        path.getFileName().toString().startsWith("l") && attrs.isRegularFile());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> fail("Expect empty stream"));
        assertEquals(pred.visited(), all);
    }
}
 
Example 7
Project: jdk8u-jdk   File: StreamTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testFind() throws IOException {
    PathBiPredicate pred = new PathBiPredicate((path, attrs) -> true);

    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        Set<Path> result = s.collect(Collectors.toCollection(TreeSet::new));
        assertEquals(pred.visited(), all);
        assertEquals(result.toArray(new Path[0]), pred.visited());
    }

    pred = new PathBiPredicate((path, attrs) -> attrs.isSymbolicLink());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> assertTrue(Files.isSymbolicLink(path)));
        assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) ->
        path.getFileName().toString().startsWith("e"));
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> assertEquals(path.getFileName().toString(), "empty"));
        assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) ->
        path.getFileName().toString().startsWith("l") && attrs.isRegularFile());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> fail("Expect empty stream"));
        assertEquals(pred.visited(), all);
    }
}
 
Example 8
Project: buck   File: ModernBuildRuleIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotDeleteTemporaryFilesIfOptionIsFalse() throws Exception {
  // When not deleting temporary files, ensure the temporary file still exist.
  workspace.runBuckBuild("--config=build.delete_temporaries=false", "//:foo").assertSuccess();
  try (Stream<Path> paths =
      Files.find(
          workspace.getPath(workspace.getBuckPaths().getScratchDir()),
          255,
          (path, basicFileAttributes) -> path.endsWith("temporary_writing_rule_temp"))) {
    Assert.assertTrue("Temporary file should still exist", paths.count() > 0);
  }
}
 
Example 9
Project: openjdk-8   File: StreamTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testFind() throws IOException {
    PathBiPredicate pred = new PathBiPredicate((path, attrs) -> true);

    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        Set<Path> result = s.collect(Collectors.toCollection(TreeSet::new));
        assertEquals(pred.visited(), all);
        assertEquals(result.toArray(new Path[0]), pred.visited());
    }

    pred = new PathBiPredicate((path, attrs) -> attrs.isSymbolicLink());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> assertTrue(Files.isSymbolicLink(path)));
        assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) ->
        path.getFileName().toString().startsWith("e"));
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> assertEquals(path.getFileName().toString(), "empty"));
        assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) ->
        path.getFileName().toString().startsWith("l") && attrs.isRegularFile());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> fail("Expect empty stream"));
        assertEquals(pred.visited(), all);
    }
}
 
Example 10
Project: jdk8u-dev-jdk   File: StreamTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testFind() throws IOException {
    PathBiPredicate pred = new PathBiPredicate((path, attrs) -> true);

    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        Set<Path> result = s.collect(Collectors.toCollection(TreeSet::new));
        assertEquals(pred.visited(), all);
        assertEquals(result.toArray(new Path[0]), pred.visited());
    }

    pred = new PathBiPredicate((path, attrs) -> attrs.isSymbolicLink());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> assertTrue(Files.isSymbolicLink(path)));
        assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) ->
        path.getFileName().toString().startsWith("e"));
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> assertEquals(path.getFileName().toString(), "empty"));
        assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) ->
        path.getFileName().toString().startsWith("l") && attrs.isRegularFile());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> fail("Expect empty stream"));
        assertEquals(pred.visited(), all);
    }
}
 
Example 11
Project: bundletool   File: SdkToolsLocator.java    License: Apache License 2.0 5 votes vote down vote up
private Optional<Path> locateBinaryOnSystemPath(
    String binaryGlob, SystemEnvironmentProvider systemEnvironmentProvider) {

  Optional<String> rawPath = systemEnvironmentProvider.getVariable(SYSTEM_PATH_VARIABLE);
  if (!rawPath.isPresent()) {
    return Optional.empty();
  }

  // Any sane Java runtime should define this property.
  String pathSeparator = systemEnvironmentProvider.getProperty("path.separator").get();

  PathMatcher binPathMatcher = fileSystem.getPathMatcher(binaryGlob);
  for (String pathDir : Splitter.on(pathSeparator).splitToList(rawPath.get())) {
    try (Stream<Path> pathStream =
        Files.find(
            fileSystem.getPath(pathDir),
            /* maxDepth= */ 1,
            (path, attributes) ->
                binPathMatcher.matches(path)
                    && Files.isExecutable(path)
                    && Files.isRegularFile(path))) {

      Optional<Path> binaryInDir = pathStream.findFirst();
      if (binaryInDir.isPresent()) {
        return binaryInDir;
      }
    } catch (NoSuchFileException | NotDirectoryException | InvalidPathException tolerate) {
      // Tolerate invalid PATH entries.
    } catch (IOException e) {
      throw CommandExecutionException.builder()
          .withCause(e)
          .withInternalMessage(
              "Error while trying to locate adb on system PATH in directory '%s'.", pathDir)
          .build();
    }
  }

  return Optional.empty();
}
 
Example 12
Project: chvote-1-0   File: OutputFilesPattern.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Tries to find a file matching a given <i>filenamePattern</i> regular expression.
 *
 * @param filenamePattern regular expression pattern that the file should match
 * @param rootPath        path from which to recursively search for the file
 * @return the first file matching the pattern from the root directory, or an empty optional if none matched
 */
public Optional<Path> findFirstFileByPattern(final Pattern filenamePattern, Path rootPath) {
    try (Stream<Path> pathStream = Files.find(
            rootPath,
            FIND_FILES_MAX_DEPTH,
            (path, attr) -> filenamePattern.matcher(path.getFileName().toString()).matches())) {
        return pathStream.sorted().findFirst();
    } catch (IOException e) {
        throw new FileOperationRuntimeException("Cannot walk file tree", e);
    }
}
 
Example 13
Project: Spring-5.0-Cookbook   File: EmployeeFileStreamService.java    License: MIT License 5 votes vote down vote up
public String searchFilesDir(String filePath, String extension) throws IOException{
	Path root = Paths.get(filePath);
	int depth = 3;
	Stream<Path> searchStream = Files.find(root, depth, (path, attr) ->
	        String.valueOf(path).endsWith(extension));
	String found = searchStream
	        .sorted()
	        .map(String::valueOf)
	        .collect(Collectors.joining(" / "));
	searchStream.close();
	return found;
}
 
Example 14
Project: mycore   File: MCRTransferPackageUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a list containing all paths to the classifications which should be imported.
 * 
 * @param targetDirectory
 *                the directory where the *.tar was unpacked
 * @return list of paths
 * @throws IOException
 *                if an I/O error is thrown when accessing one of the files
 */
public static List<Path> getClassifications(Path targetDirectory) throws IOException {
    List<Path> classificationPaths = new ArrayList<>();
    Path classPath = targetDirectory.resolve(MCRTransferPackage.CLASS_PATH);
    if (Files.exists(classPath)) {
        try (Stream<Path> stream = Files.find(classPath, 2,
            (path, attr) -> path.toString().endsWith(".xml") && Files.isRegularFile(path))) {
            stream.forEach(classificationPaths::add);
        }
    }
    return classificationPaths;
}
 
Example 15
Project: centraldogma   File: Change.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link List} of upsert {@link Change}s from all files under the specified directory
 * recursively.
 *
 * @param sourcePath the path to the import directory
 * @param targetPath the target directory path of the imported {@link Change}s
 *
 * @throws IOError if I/O error occurs
 */
static List<Change<?>> fromDirectory(Path sourcePath, String targetPath) {
    requireNonNull(sourcePath, "sourcePath");
    validateDirPath(targetPath, "targetPath");

    if (!Files.isDirectory(sourcePath)) {
        throw new IllegalArgumentException("sourcePath: " + sourcePath + " (must be a directory)");
    }

    final String finalTargetPath;
    if (!targetPath.endsWith("/")) {
        finalTargetPath = targetPath + '/';
    } else {
        finalTargetPath = targetPath;
    }

    try (Stream<Path> s = Files.find(sourcePath, Integer.MAX_VALUE, (p, a) -> a.isRegularFile())) {
        final int baseLength = sourcePath.toString().length() + 1;
        return s.map(sourceFilePath -> {
            final String targetFilePath =
                    finalTargetPath +
                    sourceFilePath.toString().substring(baseLength).replace(File.separatorChar, '/');

            return fromFile(sourceFilePath, targetFilePath);
        }).collect(Collectors.toList());
    } catch (IOException e) {
        throw new IOError(e);
    }
}
 
Example 16
Project: javacore   File: Files1.java    License: Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
private static void testFind() throws IOException {
    Path start = Paths.get("");
    int maxDepth = 5;
    try (Stream<Path> stream = Files.find(start, maxDepth, (path, attr) -> String.valueOf(path).endsWith(".js"))) {
        String joined = stream.sorted().map(String::valueOf).collect(Collectors.joining("; "));
        System.out.println("find(): " + joined);
    }
}
 
Example 17
Project: hottub   File: StreamTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testFind() throws IOException {
    PathBiPredicate pred = new PathBiPredicate((path, attrs) -> true);

    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        Set<Path> result = s.collect(Collectors.toCollection(TreeSet::new));
        assertEquals(pred.visited(), all);
        assertEquals(result.toArray(new Path[0]), pred.visited());
    }

    pred = new PathBiPredicate((path, attrs) -> attrs.isSymbolicLink());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> assertTrue(Files.isSymbolicLink(path)));
        assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) ->
        path.getFileName().toString().startsWith("e"));
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> assertEquals(path.getFileName().toString(), "empty"));
        assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) ->
        path.getFileName().toString().startsWith("l") && attrs.isRegularFile());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> fail("Expect empty stream"));
        assertEquals(pred.visited(), all);
    }
}
 
Example 18
Project: openjdk-8-source   File: StreamTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testFind() throws IOException {
    PathBiPredicate pred = new PathBiPredicate((path, attrs) -> true);

    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        Set<Path> result = s.collect(Collectors.toCollection(TreeSet::new));
        assertEquals(pred.visited(), all);
        assertEquals(result.toArray(new Path[0]), pred.visited());
    }

    pred = new PathBiPredicate((path, attrs) -> attrs.isSymbolicLink());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> assertTrue(Files.isSymbolicLink(path)));
        assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) ->
        path.getFileName().toString().startsWith("e"));
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> assertEquals(path.getFileName().toString(), "empty"));
        assertEquals(pred.visited(), all);
    }

    pred = new PathBiPredicate((path, attrs) ->
        path.getFileName().toString().startsWith("l") && attrs.isRegularFile());
    try (Stream<Path> s = Files.find(testFolder, Integer.MAX_VALUE, pred)) {
        s.forEach(path -> fail("Expect empty stream"));
        assertEquals(pred.visited(), all);
    }
}
 
Example 19
Project: bazel   File: SourceCompilationUnit.java    License: Apache License 2.0 4 votes vote down vote up
/** Compiles Java source files and write to the pre-specified path to the output jar. */
Path compile() throws IOException, SourceCompilationException {
  Path compilationStdOut = Files.createTempFile("compilation_stdout_", ".txt");
  Path compilationStdErr = Files.createTempFile("compilation_stderr_", ".txt");
  Path compiledRootDir = Files.createTempDirectory("compilation_prodout_");
  ImmutableList<String> javacOptions =
      ImmutableList.<String>builder()
          .addAll(customJavacOptions)
          .add("-d " + compiledRootDir)
          .build();
  final List<Path> compiledFiles;
  try (OutputStream stdOutStream = Files.newOutputStream(compilationStdOut);
      OutputStream stdErrStream = Files.newOutputStream(compilationStdErr)) {
    Splitter splitter = Splitter.on(" ").trimResults().omitEmptyStrings();
    ImmutableList<String> compilationArguments =
        ImmutableList.<String>builder()
            .addAll(splitter.split(String.join(" ", javacOptions)))
            .addAll(sourceInputs.stream().map(Path::toString).collect(Collectors.toList()))
            .build();
    compiler.run(
        nullInputStream(),
        stdOutStream,
        stdErrStream,
        compilationArguments.toArray(new String[0]));
    int maxDepth = sourceInputs.stream().mapToInt(Path::getNameCount).max().getAsInt();
    try (Stream<Path> outputStream =
        Files.find(compiledRootDir, maxDepth, (path, fileAttr) -> true)) {
      compiledFiles = outputStream.collect(Collectors.toList());
    }
    try (JarOutputStream jarOutputStream =
        new JarOutputStream(Files.newOutputStream(outputJar))) {
      for (Path compiledFile : compiledFiles) {
        try (InputStream inputStream = Files.newInputStream(compiledFile)) {
          Path inArchivalPath = compiledRootDir.relativize(compiledFile);
          JarEntry jarEntry = new JarEntry(inArchivalPath.toString());
          jarOutputStream.putNextEntry(jarEntry);
          if (!Files.isDirectory(compiledFile)) {
            ByteStreams.copy(inputStream, jarOutputStream);
          }
          jarOutputStream.closeEntry();
        }
      }
    }
  }
  String compilationStandardErrorMessage =
      new String(Files.readAllBytes(compilationStdErr), Charset.defaultCharset());
  if (!compilationStandardErrorMessage.isEmpty()) {
    throw new SourceCompilationException(compilationStandardErrorMessage);
  }
  return outputJar;
}
 
Example 20
Project: ariADDna   File: LocalStoreIndexingService.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * return files created after the date
 *
 * @param dir  directory for search
 * @param date date
 * @return collection of files
 * @throws IOException
 */
public List<Path> findFilesByCreateDate(Path dir, Date date) throws IOException {
    try (Stream<Path> paths = Files.find(dir, Integer.MAX_VALUE,
            (path, basicFileAttributes) -> basicFileAttributes.creationTime().toMillis() >= date
                    .getTime())) {
        return paths.collect(Collectors.toList());
    }
}