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

The following examples show how to use java.nio.file.Files#walk() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: waltz   File: SpdxLicenceImporter.java    License: Apache License 2.0 6 votes vote down vote up
private List<SpdxLicence> parseData(String directoryPath) throws IOException, URISyntaxException {
    URI directoryUrl = this.getClass().getClassLoader().getResource(directoryPath).toURI();

    try (Stream<Path> paths = Files.walk(Paths.get(directoryUrl))) {

        List<SpdxLicence> spdxLicences = paths
                .filter(Files::isRegularFile)
                .map(this::parseSpdxLicence)
                .filter(l -> l.isPresent())
                .map(l -> l.get())
                .collect(toList());

        System.out.printf("Parsed %s SPDX licence files \n", spdxLicences.size());
        return spdxLicences;
    }
}
 
Example 2
public static ArrayList<Path> fileListDeep(Path dir) throws IOException {
    if (!Files.exists(dir)) {
        throw new IOException("Attempted to list files of a directory that does not exist");
    }

    Stream<Path> ds = Files.walk(dir);

    ArrayList<Path> dirList = new ArrayList<>();

    Iterator<Path> it = ds.iterator();
    while (it.hasNext()) {
        Path tp = it.next();
        // discard directories
        if (!Files.isDirectory(tp)) {
            dirList.add(tp);
        }
    }
    ds.close();
    return dirList;
}
 
Example 3
@SuppressFBWarnings("RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE") // Bug in spotbugs for try-with-resources
private List<Path> getFilesInDirectory(Path directory) throws IOException {
  try (Stream<Path> walk = Files.walk(directory)) {
    return walk.filter(Files::isRegularFile)
        .collect(Collectors.toList());
  }
}
 
Example 4
@NotNull
static Optional<Path> getPath(@NotNull final String path, @NotNull final String prefix, @NotNull final String suffix) {
    Stream<Path> paths;
    try {
        paths = Files.walk(new File(path).toPath());
    } catch (IOException e) {
        return Optional.empty();
    }
    return paths.filter(filePath -> filePath.getFileName().toString().startsWith(prefix) && filePath.getFileName()
            .toString()
            .endsWith(suffix) && filePath.toString().contains(path + File.separator + prefix)).findFirst();
}
 
Example 5
Source Project: cactoos   File: Directory.java    License: MIT License 5 votes vote down vote up
@Override
public Iterator<Path> iterator() {
    try (Stream<Path> files = Files.walk(this.dir)) {
        return files.collect(Collectors.toList()).iterator();
    } catch (final IOException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example 6
Source Project: quarkus   File: QuarkusProdModeTest.java    License: Apache License 2.0 5 votes vote down vote up
private void exportArchive(Path deploymentDir, Class<?> testClass) {
    try {
        JavaArchive archive = getArchiveProducerOrDefault();
        if (customApplicationProperties != null) {
            archive.add(new PropertiesAsset(customApplicationProperties), "application.properties");
        }
        archive.as(ExplodedExporter.class).exportExplodedInto(deploymentDir.toFile());

        String exportPath = System.getProperty("quarkus.deploymentExportPath");
        if (exportPath != null) {
            File exportDir = new File(exportPath);
            if (exportDir.exists()) {
                if (!exportDir.isDirectory()) {
                    throw new IllegalStateException("Export path is not a directory: " + exportPath);
                }
                try (Stream<Path> stream = Files.walk(exportDir.toPath())) {
                    stream.sorted(Comparator.reverseOrder()).map(Path::toFile)
                            .forEach(File::delete);
                }
            } else if (!exportDir.mkdirs()) {
                throw new IllegalStateException("Export path could not be created: " + exportPath);
            }
            File exportFile = new File(exportDir, archive.getName());
            archive.as(ZipExporter.class).exportTo(exportFile);
        }
    } catch (Exception e) {
        throw new RuntimeException("Unable to create the archive", e);
    }
}
 
Example 7
public void testWalkFollowLink() {
    // If link is not supported, the directory structure won't have link.
    // We still want to test the behavior with FOLLOW_LINKS option.
    try (Stream<Path> s = Files.walk(testFolder, FileVisitOption.FOLLOW_LINKS)) {
        Object[] actual = s.sorted().toArray();
        assertEquals(actual, all_folowLinks);
    } catch (IOException ioe) {
        fail("Unexpected IOException");
    }
}
 
Example 8
Source Project: centraldogma   File: TemporaryFolder.java    License: Apache License 2.0 5 votes vote down vote up
public void delete() throws IOException {
    if (root == null) {
        return;
    }

    try (Stream<Path> walk = Files.walk(root)) {
        walk.sorted(Comparator.reverseOrder())
            .map(Path::toFile)
            .forEach(File::delete);
    }

    root = null;
}
 
Example 9
Source Project: spring-batch   File: FileDeletingTasklet.java    License: MIT License 5 votes vote down vote up
@Override
public RepeatStatus execute(StepContribution stepContribution,
    ChunkContext chunkContext) {
  try (Stream<Path> walk =
      Files.walk(Paths.get(directory.getFile().getPath()))) {
    walk.filter(Files::isRegularFile).map(Path::toFile)
        .forEach(File::delete);
  } catch (IOException e) {
    LOGGER.error("error deleting files", e);
    throw new UnexpectedJobExecutionException(
        "unable to delete files");
  }

  return RepeatStatus.FINISHED;
}
 
Example 10
private void train(String user, Path folder, TrainingKind trainingKind) throws IOException {
    spamAssassinContainer.getDockerClient().copyArchiveToContainerCmd(spamAssassinContainer.getContainerId())
        .withHostResource(folder.toAbsolutePath().toString())
        .withRemotePath("/root")
        .exec();
    try (Stream<Path> paths = Files.walk(folder)) {
        paths
            .filter(Files::isRegularFile)
            .map(Path::toFile)
            .forEach(Throwing.consumer(file -> spamAssassinContainer.execInContainer("sa-learn",
                trainingKind.saLearnExtensionName(), "-u", user,
                "/root/" + trainingKind.name().toLowerCase(Locale.US) + "/" +  file.getName())));
    }
}
 
Example 11
public void testWalkOneLevel() {
    try (Stream<Path> s = Files.walk(testFolder, 1)) {
        Object[] actual = s.filter(path -> ! path.equals(testFolder))
                           .sorted()
                           .toArray();
        assertEquals(actual, level1);
    } catch (IOException ioe) {
        fail("Unexpected IOException");
    }
}
 
Example 12
private Set<Path> toListOfPaths(DirectoryStream<Path> directoryStream) {
    Set<Path> directories = new HashSet<>();
    for (Path p : directoryStream) {
        try (Stream<Path> paths = Files.walk(p)) {
            Set<Path> tree = paths.filter(Files::isDirectory)
                    .collect(Collectors.toSet());
            directories.addAll(tree);
        } catch (IOException ex) {
            LOG.errorf("Ignoring directory [{0}] - {1}", new Object[] { p.getFileName().toString(), ex.getMessage() });
        }
    }
    return directories;
}
 
Example 13
public void test() throws Exception {
    // JPRT not yet ready for jmods
    Helper helper = Helper.newHelper();
    if (helper == null) {
        System.err.println("Test not run, NO jmods directory");
        return;
    }

    List<String> classes = Arrays.asList("toto.Main", "toto.com.foo.bar.X");
    Path moduleFile = helper.generateModuleCompiledClasses(
            helper.getJmodSrcDir(), helper.getJmodClassesDir(), "leaf1", classes);
    Path moduleInfo = moduleFile.resolve("module-info.class");

    // Classes have been compiled in debug.
    List<Path> covered = new ArrayList<>();
    byte[] infoContent = Files.readAllBytes(moduleInfo);
    try (Stream<Path> stream = Files.walk(moduleFile)) {
        for (Iterator<Path> iterator = stream.iterator(); iterator.hasNext(); ) {
            Path p = iterator.next();
            if (Files.isRegularFile(p) && p.toString().endsWith(".class")) {
                byte[] content = Files.readAllBytes(p);
                String path = "/" + helper.getJmodClassesDir().relativize(p).toString();
                String moduleInfoPath = path + "/module-info.class";
                check(path, content, moduleInfoPath, infoContent);
                covered.add(p);
            }
        }
    }
    if (covered.isEmpty()) {
        throw new AssertionError("No class to compress");
    } else {
        System.err.println("removed debug attributes from "
                + covered.size() + " classes");
    }
}
 
Example 14
public void init() {
	files = new ArrayList<>();
	
	try {
		Stream<Path> paths = Files.walk(BleachFileMang.getDir().resolve("notebot"));
		paths.forEach(p -> files.add(p.getFileName().toString()));
		paths.close();
		files.remove(0);
	} catch (IOException e) {}
	
	windows.clear();
	windows.add(new Window(width / 4, height / 4 - 10, width / 4 + width / 2, height / 4 + height / 2, "Notebot Gui", new ItemStack(Items.NOTE_BLOCK)));
}
 
Example 15
private static void deleteDirectoryContent(Path directory) throws IOException {
    Log.debug("deleting %s", directory);
    try (Stream<Path> stream = Files.walk(directory)) {
        stream.sorted(Comparator.reverseOrder())
              .filter(file -> !file.equals(directory))
              .forEach(file -> {
                  try {
                      Files.delete(file);
                  } catch (IOException e) {
                      throw new UncheckedIOException(e);
                  }
              });
    }
}
 
Example 16
Source Project: hottub   File: StreamTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testWalk() {
    try (Stream<Path> s = Files.walk(testFolder)) {
        Object[] actual = s.sorted().toArray();
        assertEquals(actual, all);
    } catch (IOException ioe) {
        fail("Unexpected IOException");
    }
}
 
Example 17
Source Project: n4js   File: FileDeleter.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Requests that the resource denoted by the given path be deleted upon (normal) termination of the Java virtual
 * machine. If the given path denotes a non-empty directory, its entire contents will be deleted as well.
 */
public static void deleteOnExit(Path resourceToDelete) throws IOException {
	final File resourceToDeleteAsFile = resourceToDelete.toFile();
	if (resourceToDeleteAsFile.isDirectory()) {
		try (Stream<Path> walker = Files.walk(resourceToDelete)) {
			walker.forEachOrdered(path -> path.toFile().deleteOnExit());
		}
	} else {
		resourceToDeleteAsFile.deleteOnExit();
	}
}
 
Example 18
Stream<Path> silentFilesWalk(Path dir) throws IllegalStateException {
    try {
        return Files.walk(dir);
    } catch (IOException ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example 19
private static List<File> getSystemJars() throws IOException {
  Config config = Config.load();

  if (config.isJava8()) {
    final String javaHome = config.getJavaHomeDir();
    final File jvmDir = new File(javaHome);
    final String toolsJarPath = Joiner.on(File.separator).join("..", "lib", "tools.jar");
    final File toolsJar = new File(jvmDir, toolsJarPath);

    try (final Stream<Path> stream = Files.walk(jvmDir.toPath())) {
      final List<File> files =
          stream
              .map(Path::toFile)
              .filter(
                  f ->
                      f.getName().endsWith(FileUtils.JAR_EXT)
                          && !f.getName().endsWith("policy.jar"))
              .collect(Collectors.toList());
      files.add(toolsJar.getCanonicalFile());
      return files;
    }
  } else {
    List<File> result = new ArrayList<>(1);
    result.add(ModuleHelper.getJrtFsFile());
    return result;
  }
}
 
Example 20
Source Project: jdk8u60   File: StreamTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testWalkFollowLink() {
    // If link is not supported, the directory structure won't have link.
    // We still want to test the behavior with FOLLOW_LINKS option.
    try (Stream<Path> s = Files.walk(testFolder, FileVisitOption.FOLLOW_LINKS)) {
        Object[] actual = s.sorted().toArray();
        assertEquals(actual, all_folowLinks);
    } catch (IOException ioe) {
        fail("Unexpected IOException");
    }
}