Example usage for java.nio.file Files walk

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

Introduction

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

Prototype

public static Stream<Path> walk(Path start, FileVisitOption... options) throws IOException 

Source Link

Document

Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Path start = Paths.get("c:/Java_Dev/run.bat");
    int maxDepth = 5;
    long fileCount = Files.walk(start, maxDepth).filter(path -> String.valueOf(path).endsWith("xls")).count();
    System.out.format("XLS files found: %s", fileCount);
}

From source file:file.FileOperatorTest.java

/**
 *http://stackoverflow.com/questions/16524065/is-filevisitoption-follow-links-the-only-filevisitoption-available
 *//*from  www. j  a  va2s  .  c om*/
public static List<Path> testWalkFileWithStream() {
    try {
        System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "20");
        long a = System.currentTimeMillis();
        Files.walk(Paths.get(ROOT_DIR), FileVisitOption.FOLLOW_LINKS).parallel().filter(x -> {
            return x.toFile().isFile();
        }).forEach(x -> {
            // Files.copy(x, Paths.get(""), CopyOption )
        });
        long b = System.currentTimeMillis();
        System.out.println(":" + (b - a));
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.ppojo.FolderTemplateFileQuery.java

@Override
public Set<String> getTemplateFiles() {
    CheckFolderExists();//from   w  w w.j  ava 2s.  co  m
    Set<String> result;
    FileFilter fileFilter = new WildcardFileFilter(_fileFilter);
    try {
        result = Files.walk(Paths.get(_path), _isRecursive ? Integer.MAX_VALUE : 1)
                .map(p -> new File(p.toUri())).filter(f -> fileFilter.accept(f)).map(f -> f.getAbsolutePath())
                .collect(Collectors.toSet());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:org.opentestsystem.ap.ivs.task.ItemCleanupTask.java

private void cleanupFolder(final Path rootPath, final Date cleanupThresholdDate) {
    log.debug("cleanupFolder: path {}, threshold {}", rootPath, cleanupThresholdDate);
    try {//from   www.  j  a  v a2s .c o  m
        Files.walk(rootPath, 2).filter(Files::isDirectory).filter(isPathNotEqual(rootPath))
                .filter(isFolderOlderThan(cleanupThresholdDate)).forEach(RepositoryUtil::deleteDirectory);
    } catch (IOException e) {
        log.debug("cleanupFolder: Folder not found: {}", e.getMessage());
    }
}

From source file:org.opentestsystem.ap.irs.task.ItemCleanupTask.java

private void cleanupFolder(final Path rootPath, final Date cleanupThresholdDate) {
    log.debug("cleanupFolder: path {}, threshold {}", rootPath, cleanupThresholdDate);
    try {/*  w w w .ja  va 2 s .  c o m*/
        Files.walk(rootPath, 1).filter(Files::isDirectory).filter(isPathNotEqual(rootPath))
                .filter(isFolderOlderThan(cleanupThresholdDate)).forEach(RepositoryUtil::deleteDirectory);
    } catch (IOException e) {
        log.debug("cleanupFolder: Folder not found: {}", e.getMessage());
    }
}

From source file:org.artifactory.support.core.compression.CompressionServiceImpl.java

/**
 * Performs cleanup//from w  ww.j av  a  2  s .  com
 *
 * @param directory content to clean
 */
private void cleanup(File directory) {
    try {
        Files.walk(directory.toPath(), FileVisitOption.FOLLOW_LINKS).filter(Files::isDirectory)
                .filter(p -> !p.equals(directory.toPath()))
                .filter(p -> !FilenameUtils.getExtension(p.toString()).equals("zip")).forEach(p -> {
                    try {
                        FileUtils.deleteDirectory(p.toFile());
                    } catch (IOException e) {
                        log.debug("Cannot delete folder: {}", e);
                    }
                });
    } catch (IOException e) {
        log.debug("Cleanup has failed: {}", e);
    }
}

From source file:net.geoprism.localization.LocaleManager.java

private Collection<Locale> loadCLDRs() {
    try {/*from   w w w .  ja v  a2 s .com*/

        // Get the list of known CLDR locale
        Set<Locale> locales = new HashSet<Locale>();

        Set<String> paths = new HashSet<String>();

        URL resource = this.getClass().getResource("/cldr/main");
        URI uri = resource.toURI();

        if (uri.getScheme().equals("jar")) {
            FileSystem fileSystem = FileSystems.newFileSystem(uri, new HashMap<String, Object>());
            Path path = fileSystem.getPath("/cldr/main");

            Stream<Path> walk = Files.walk(path, 1);

            try {
                for (Iterator<Path> it = walk.iterator(); it.hasNext();) {
                    Path location = it.next();

                    paths.add(location.toAbsolutePath().toString());
                }
            } finally {
                walk.close();
            }
        } else {
            String url = resource.getPath();
            File root = new File(url);

            File[] files = root.listFiles(new DirectoryFilter());

            if (files != null) {
                for (File file : files) {
                    paths.add(file.getAbsolutePath());
                }
            }
        }

        for (String path : paths) {
            File file = new File(path);

            String filename = file.getName();

            locales.add(LocaleManager.getLocaleForName(filename));
        }

        return locales;
    } catch (Exception e) {
        throw new ProgrammingErrorException(e);
    }
}

From source file:org.opendatakit.briefcase.reused.UncheckedFiles.java

public static Stream<Path> walk(Path path, FileVisitOption... options) {
    try {/*from  w  w  w  .j  a v a  2 s.  c om*/
        return Files.walk(path, options);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.structr.web.maintenance.BulkMoveUnusedFilesCommand.java

@Override
public void execute(final Map<String, Object> properties) throws FrameworkException {

    String mode = (String) properties.get("mode");
    String targetDir = (String) properties.get("target");

    if (StringUtils.isBlank(mode)) {
        // default
        mode = "log";
    }/*from w  ww.j  a  va  2s. co  m*/

    if (StringUtils.isBlank(targetDir)) {
        // default
        targetDir = "unused";
    }

    logger.log(Level.INFO, "Starting moving of unused files...");

    final DatabaseService graphDb = (DatabaseService) arguments.get("graphDb");
    final App app = StructrApp.getInstance();

    final String filesLocation = StructrApp.getConfigurationValue(Services.FILES_PATH);

    final Set<String> filePaths = new TreeSet<>();

    if (graphDb != null) {

        List<FileBase> fileNodes = null;

        try (final Tx tx = StructrApp.getInstance().tx()) {

            fileNodes = app.nodeQuery(FileBase.class, false).getAsList();

            for (final FileBase fileNode : fileNodes) {

                final String relativeFilePath = fileNode.getProperty(FileBase.relativeFilePath);

                if (relativeFilePath != null) {
                    filePaths.add(relativeFilePath);
                }
            }

            tx.success();
        }

        final List<Path> files = new LinkedList<>();

        try {

            Files.walk(Paths.get(filesLocation), FileVisitOption.FOLLOW_LINKS).filter(Files::isRegularFile)
                    .forEach((Path file) -> {
                        files.add(file);
                    });

        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }

        Path targetDirPath = null;

        if (targetDir.startsWith("/")) {
            targetDirPath = Paths.get(targetDir);
        } else {
            targetDirPath = Paths.get(filesLocation, targetDir);

        }

        if (mode.equals("move") && !Files.exists(targetDirPath)) {

            try {
                targetDirPath = Files.createDirectory(targetDirPath);

            } catch (IOException ex) {
                logger.log(Level.INFO, "Could not create target directory {0}: {1}",
                        new Object[] { targetDir, ex });
                return;
            }
        }

        for (final Path file : files) {

            final String filePath = file.toString();
            final String relPath = StringUtils.stripStart(filePath.substring(filesLocation.length()), "/");

            //System.out.println("files location: " + filesLocation + ", file path: " + filePath + ", rel path: " + relPath);
            if (!filePaths.contains(relPath)) {

                if (mode.equals("log")) {

                    System.out
                            .println("File " + file + " doesn't exist in database (rel path: " + relPath + ")");

                } else if (mode.equals("move")) {

                    try {
                        final Path targetPath = Paths.get(targetDirPath.toString(),
                                file.getFileName().toString());

                        Files.move(file, targetPath);

                        System.out.println("File " + file.getFileName() + " moved to " + targetPath);

                    } catch (IOException ex) {
                        logger.log(Level.INFO, "Could not move file {0} to target directory {1}: {2}",
                                new Object[] { file, targetDir, ex });
                    }

                }
            }

        }

    }

    logger.log(Level.INFO, "Done");
}

From source file:com.jvms.i18neditor.Editor.java

public void importResources(Path dir) {
    if (!closeCurrentSession()) {
        return;/*from  w ww.  j  av a  2 s .co m*/
    }
    if (Files.isDirectory(dir, LinkOption.NOFOLLOW_LINKS)) {
        reset();
        resourcesDir = dir;
    } else {
        showError(MessageBundle.get("resources.open.error.multiple"));
        return;
    }
    try {
        Files.walk(resourcesDir, 1).filter(path -> Resources.isResource(path)).forEach(path -> {
            try {
                Resource resource = Resources.read(path);
                setupResource(resource);
            } catch (Exception e) {
                e.printStackTrace();
                showError(MessageBundle.get("resources.open.error.single", path.toString()));
            }
        });

        List<String> recentDirs = settings.getListProperty("history");
        recentDirs.remove(resourcesDir);
        recentDirs.add(resourcesDir.toString());
        if (recentDirs.size() > 5) {
            recentDirs.remove(0);
        }
        settings.setProperty("history", recentDirs);
        editorMenu.setRecentItems(Lists.reverse(recentDirs));

        Map<String, String> keys = Maps.newTreeMap();
        resources.forEach(resource -> keys.putAll(resource.getTranslations()));
        List<String> keyList = Lists.newArrayList(keys.keySet());
        translationTree.setModel(new TranslationTreeModel(keyList));

        updateUI();
    } catch (IOException e) {
        e.printStackTrace();
        showError(MessageBundle.get("resources.open.error.multiple"));
    }
}