Example usage for java.nio.file Files list

List of usage examples for java.nio.file Files list

Introduction

In this page you can find the example usage for java.nio.file Files list.

Prototype

public static Stream<Path> list(Path dir) throws IOException 

Source Link

Document

Return a lazily populated Stream , the elements of which are the entries in the directory.

Usage

From source file:objective.taskboard.rules.CleanupDataFolderRule.java

@Override
protected void after() {
    if (beforeList == Collections.<Path>emptyList()) {
        FileUtils.deleteQuietly(folder.toFile());
    } else {/* w  w  w . ja  va 2s.co  m*/
        try {
            Files.list(folder).filter(file -> !beforeList.contains(file))
                    .forEach(newFile -> FileUtils.deleteQuietly(newFile.toFile()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:notaql.performance.PerformanceTest.java

public static void runTests() throws URISyntaxException, IOException {
    URI basePath = NotaQL.class.getResource(BASE_PATH).toURI();

    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    FileSystem zipfs = FileSystems.newFileSystem(basePath, env);

    final List<Path> tests = Files.list(Paths.get(basePath)).filter(p -> p.toString().endsWith(".json"))
            .sorted((a, b) -> a.toString().compareTo(b.toString())).collect(Collectors.toList());

    List<String> csv = new LinkedList<>();

    for (Path test : tests) {
        if (testCase != null && !test.getFileName().toString().equals(testCase))
            continue;

        final List<JSONObject> transformations = readArray(test);

        csv.add(test.getFileName().toString());

        int i = 1;

        for (JSONObject transformation : transformations) {
            final String name = transformation.getString("name");
            final String notaqlTransformation = composeTransformation(transformation);

            if (!(inEngine == null && outEngine == null
                    || inEngine != null/*from  ww  w.  j av a 2  s  . c o m*/
                            && transformation.getJSONObject("IN-ENGINE").getString("engine").equals(inEngine)
                    || outEngine != null && transformation.getJSONObject("OUT-ENGINE").getString("engine")
                            .equals(outEngine)))
                continue;

            System.out.println("Evaluation test (" + i++ + "/" + transformations.size() + "): "
                    + test.getFileName() + ": " + name);

            List<Duration> durations = new LinkedList<>();

            for (int j = 0; j < RUNS; j++) {
                clean(transformation);

                final Instant startTime = Instant.now();

                NotaQL.evaluate(notaqlTransformation);

                final Instant endTime = Instant.now();

                final Duration duration = Duration.between(startTime, endTime);

                durations.add(duration);

                System.out.println("Testrun(" + j + ") " + name + " took: " + duration);
            }

            System.out.println("!!=================================================================!!");

            System.out.println("Test " + name + " took: "
                    + durations.stream().map(Duration::toString).collect(Collectors.joining(", ")));

            System.out.println("Test " + name + " took millis: " + durations.stream()
                    .map(d -> Long.toString(d.toMillis())).collect(Collectors.joining(", ")));

            System.out.println("Test " + name + " took on average (millis): "
                    + durations.stream().mapToLong(Duration::toMillis).average());

            System.out.println("Test " + name + " took on average (ignoring first - millis): "
                    + durations.stream().skip(1).mapToLong(Duration::toMillis).average());

            System.out.println("!!=================================================================!!");

            csv.add(name);
            csv.add(durations.stream().map(d -> Long.toString(d.toMillis())).collect(Collectors.joining(",")));
        }

    }

    System.out.println(csv.stream().collect(Collectors.joining("\n")));
}

From source file:ubicrypt.core.TestUtils.java

public static void deleteR(final Path path) {
    try {/*from   www .ja va 2  s .  co m*/
        if (!Files.isDirectory(path)) {
            Files.deleteIfExists(path);
            return;
        }
        Files.list(path).forEach(TestUtils::deleteR);
        Files.deleteIfExists(path);
    } catch (final IOException e) {
        Throwables.propagate(e);
    }
}

From source file:org.pdfsam.configuration.EnhancedClassloaderProvider.java

static ClassLoader classLoader(ClassLoader classLoader) {
    requireNotNull(classLoader, "Cannot enhance null class loader");
    try {/*from  w  w  w. j  a  va2 s.  c  o m*/
        Path modulesPath = Optional.ofNullable(getUserSpecifiedModulesPath()).orElse(getModulesPath());
        if (!Files.isDirectory(modulesPath)) {
            LOG.warn(DefaultI18nContext.getInstance().i18n("Modules directory {0} does not exist",
                    modulesPath.toString()));
            return classLoader;
        }
        LOG.debug(DefaultI18nContext.getInstance().i18n("Loading modules from {0}", modulesPath.toString()));
        try (Stream<Path> files = Files.list(modulesPath)) {
            URL[] modules = getUrls(files);
            if (modules.length > 0) {
                LOG.trace(DefaultI18nContext.getInstance().i18n("Found modules jars {0}",
                        Arrays.toString(modules)));
                return AccessController.doPrivileged(
                        (PrivilegedAction<URLClassLoader>) () -> new URLClassLoader(modules, classLoader));
            }
        }
    } catch (IOException | URISyntaxException ex) {
        LOG.warn(DefaultI18nContext.getInstance().i18n("Error finding modules paths"), ex);
    }
    LOG.trace(DefaultI18nContext.getInstance().i18n("No module has been found"));
    return classLoader;
}

From source file:com.edduarte.argus.util.PluginLoader.java

private static Stream<Path> filesInDir(Path dir) {
    if (!dir.toFile().exists()) {
        return Stream.empty();
    }//from   w ww.j a  v a 2 s .  c om

    try {
        return Files.list(dir).flatMap(path -> path.toFile().isDirectory() ? filesInDir(path)
                : Collections.singletonList(path).stream());

    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:alliance.docs.DocumentationTest.java

@Test
public void testDocumentationIncludes() throws IOException, URISyntaxException {
    Stream<Path> docs = Files.list(getPath()).filter(f -> f.toString().endsWith(HTML_DIRECTORY));

    assertThat("Unresolved directive, FreeMarker reference or broken image found.", docs.noneMatch(f -> {
        try (Stream<String> lines = Files.lines(f)) {
            return lines.anyMatch(s -> s.contains(UNRESOLVED_DIRECTORY_MSG)
                    || s.toLowerCase().contains(FREEMARKER_MSG) || s.contains(BASE64_MISSING));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }//from  w w w  .  jav a  2s  .  c o  m
    }));
}

From source file:org.codice.ddf.test.common.KarafContainerFailureLogger.java

private Optional<Path> getLatestExamFolder() {
    try (Stream<Path> files = Files.list(EXAM_DIR)) {
        return files.filter(Files::isDirectory).max(Comparator.comparingLong(p -> p.toFile().lastModified()));
    } catch (IOException e) {
        LOGGER.error("No exam directory under {}", EXAM_DIR.toAbsolutePath());
        return Optional.empty();
    }/*from  ww  w. j a v  a 2 s .c  o m*/
}

From source file:org.compbox.actionbackup.ChronoBackupper.java

@Override
public void run() {
    if (this.threshold == 0) {
        return;/*from www.j a v a  2s .  c  om*/
    }
    try {
        final File dest;
        try {
            dest = getFileName();
        } catch (Exception e) {
            Logger.getLogger(BackupService.class.getName()).log(Level.SEVERE, null, e);
            return;
        }
        if (dest.exists()) {
            System.out.println("Destination already exists: " + dest);
            return;
        }
        System.out.println("Writing to: " + dest);
        FileUtils.copyDirectory(sourceDirectory.toFile(), dest);

        File[] listFiles = Files.list(destDirectory).filter(Files::isDirectory).sorted().map(Path::toFile)
                .toArray(File[]::new);

        if (listFiles.length > this.threshold) {
            for (int i = 0; i < listFiles.length - this.threshold; i++) {
                // System.out.println("Deleting: " + listFiles[i]);
                FileUtils.deleteDirectory(listFiles[i]);
            }
        } else {
            //System.out.println(listFiles.length);
        }
    } catch (IOException ex) {
        Logger.getLogger(BackupService.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ru.xxlabaza.popa.template.TemplaterFacade.java

@SneakyThrows
public String build(String templateName, Map<String, Object> bindings) {
    log.info("Template: '{}', bindings: {}", templateName, bindingsToString(bindings));
    val pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + templateName + extensionsPattern);
    val templatePath = Files.list(templatesFolder).filter(it -> pathMatcher.matches(it.getFileName()))
            .findFirst()/*from  www . j av a  2s. c o  m*/
            .orElseThrow(
                    () -> new FileNotFoundException(String.format("Template '%s' not found", templateName)))
            .toAbsolutePath();
    val templater = templaters.get(FileSystemUtils.getExstension(templatePath));
    return templater.build(templatesFolder.relativize(templatePath), bindings);
}

From source file:org.wso2.carbon.identity.adaptive.auth.deployer.SiddhiAppDeployer.java

private void loadSiddhiApps() {

    try {//from  w w  w  .  j a  v a 2  s  .co m
        if (Files.exists(rootPath)) {
            Files.list(rootPath).filter(Files::isRegularFile)
                    .filter(x -> x.getFileName().toString().endsWith(SIDDHI_FILE_SUFFIX))
                    .forEach(this::deploySiddhiApp);
        }
    } catch (IOException e) {
        log.error("Error while deploying siddhi apps in path: " + rootPath.toAbsolutePath(), e);
    }
}