Example usage for java.nio.file Files walkFileTree

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

Introduction

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

Prototype

public static Path walkFileTree(Path start, FileVisitor<? super Path> visitor) throws IOException 

Source Link

Document

Walks a file tree.

Usage

From source file:org.roda_project.commons_ip.utils.Utils.java

/**
 * Deletes a directory/file/*from ww  w .  jav a2 s .co  m*/
 * 
 * @param path
 *          path to the directory/file that will be deleted. in case of a
 *          directory, if not empty, everything in it will be deleted as well.
 *
 * @throws IOException
 */
public static void deletePath(Path path) throws IOException {
    if (path == null) {
        return;
    }

    try {
        Files.delete(path);

    } catch (DirectoryNotEmptyException e) {
        LOGGER.debug("Directory is not empty. Going to delete its content as well.");
        try {
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                }

            });
        } catch (IOException e1) {
            throw e1;
        }
    } catch (IOException e) {
        throw e;
    }
}

From source file:org.apache.tika.eval.TikaEvalCLITest.java

@Test
public void testProfileReports() throws Exception {
    CachingFileVisitor v = new CachingFileVisitor();
    Files.walkFileTree(profileReportsDir, v);
    int cnt = 0;/*from   w  w w.  j a  va  2  s .  c  om*/
    for (Path report : v.getPaths()) {

        if (report.getFileName().toString().endsWith(".xlsx")) {
            cnt++;
        }
    }
    assertTrue(cnt > 5);
}

From source file:org.kles.m3.service.M3ConnectorBuilderService.java

@Override
protected Task<Void> createTask() {
    return new Task<Void>() {

        @Override// w  ww  . j a  v a  2 s . c o  m
        protected Void call() throws MAKException, InterruptedException {
            beginTime = System.currentTimeMillis();
            updateMessage("Initialisation des donnes de " + m3Connector.getEnv().getName());
            m3Connector.getMapEntityByConfiguration().entrySet().stream()
                    .forEach((Map.Entry<M3ConfigurationInfo, M3ConfigurationDetail> key) -> {

                        if (key.getKey().getName().equals(m3Connector.getMainConfig().getName())
                                && !m3Connector.getMainConfig().getName().equals("MVX")) {
                            ArrayList<M3ClassPathEntry> l = new ArrayList<>();
                            for (Map.Entry<String, M3Component> component : key.getValue().getListComponent()
                                    .entrySet()) {
                                if (m3Connector.getListComponentSelect().contains(component.getValue())
                                        && !component.getValue().getNameComponent().equals("MVX")) {
                                    l.addAll(component.getValue().getListComponentPath());
                                }
                            }
                            key.getValue().setConfigClassPath(l);
                        } else {
                            key.getValue().setConfigClassPath(key.getValue().getCompleteClassPath());
                        }
                        ArrayList<Path> arrayPath = new ArrayList<>();
                        ProcessFile fileProcessor = new ProcessFile();
                        fileProcessor.setExtFilter(".class");
                        for (M3ClassPathEntry cl1 : key.getValue().getConfigClassPath()) {
                            try {
                                if (new File(cl1.getPath().toOSString()).exists()) {
                                    updateMessage("Recherche d'objets dans " + cl1.getPath().toOSString());
                                    Files.walkFileTree(Paths.get(cl1.getPath().toString()), fileProcessor);
                                }
                            } catch (IOException ex) {
                                Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex);
                            }
                            arrayPath.addAll(fileProcessor.getList());
                        }

                        int cpt = 0;
                        for (Path p : arrayPath) {
                            updateMessage("Traitement des objets de " + p.toString());
                            LinkedHashMap<String, SourceObject> entity = key.getValue().getMapEntity()
                                    .get(M3Utils.getPgmType(p.toFile().getAbsolutePath()));
                            if (entity != null) {
                                String name = FilenameUtils.getBaseName(p.toString());
                                if (!entity.containsKey(name)) {
                                    if (M3Utils.getPgmType(p.toFile().getAbsolutePath()).equals(Resource.DB)
                                            && name.contains("$")) {
                                        continue;
                                    }
                                    SourceObject obj = new SourceObject();
                                    obj.setObjectPath(p);
                                    entity.put(name, obj);
                                    cpt++;
                                }
                            }
                        }
                        updateMessage(cpt + " objets trouvs appartenant  la configuration "
                                + key.getKey().getName() + "(" + key.getKey().getName() + ")");
                    });
            updateMessage("Fin de la recherche d'objet");
            Thread.sleep(2000);
            return null;
            /*beginTime = System.currentTimeMillis();
             updateMessage("Initialisation des donnes");
             m3Connector.getMapEntityByConfiguration().entrySet().stream().forEach((key) -> {
                    
             ArrayList<Path> arrayPath = new ArrayList<>();
             ProcessFile fileProcessor = new ProcessFile();
             fileProcessor.setExtFilter(".class");
             for (M3ClassPathEntry cl1 : key.getValue().getConfigClassPath()) {
             try {
             if (new File(cl1.getPath().toOSString()).exists()) {
             updateMessage("Recherche d'objets dans " + cl1.getPath().toOSString());
             Files.walkFileTree(Paths.get(cl1.getPath().toString()), fileProcessor);
             }
             } catch (IOException ex) {
             Logger.getLogger(Process.class.getName()).log(Level.SEVERE, null, ex);
             }
             arrayPath.addAll(fileProcessor.getList());
             }
                    
             int cpt = 0;
             for (Path p : arrayPath) {
             updateMessage("Traitement des objets de " + p.toString());
             LinkedHashMap<String, SourceObject> entity = key.getValue().getMapEntity().get(M3Utils.getPgmType(p.toFile().getAbsolutePath()));
             if (entity != null) {
             String name = FilenameUtils.getBaseName(p.toString());
             if (!entity.containsKey(name)) {
             if (M3Utils.getPgmType(p.toFile().getAbsolutePath()).equals(Resource.DB) && name.contains("$")) {
             continue;
             }
             SourceObject obj = new SourceObject();
             obj.setObjectPath(p);
             entity.put(name, obj);
             cpt++;
             }
             }
             }
             updateMessage(cpt + " objets trouvs appartenant  la configuration " + key.getKey().getName() + "(" + key.getKey().getName() + ")");
             });
             updateMessage("Fin de la recherche d'objet");
             Thread.sleep(2000);
             return null;*/
        }
    };
}

From source file:org.apdplat.superword.tools.PdfParser.java

public static void parseDirectory(Path dir) {
    try {/*  w ww .ja v  a 2  s . c o m*/
        long start = System.currentTimeMillis();
        LOGGER.info("?" + dir);
        List<String> fileNames = new ArrayList<>();
        Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String fileName = parseFile(file);
                if (StringUtils.isNotBlank(fileName)) {
                    fileNames.add(fileName);
                }
                return FileVisitResult.CONTINUE;
            }

        });
        Files.write(Paths.get("src/main/resources/it/manifest"), fileNames);
        long cost = System.currentTimeMillis() - start;
        LOGGER.info("?" + cost + "");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.sonar.process.FileUtils.java

private static void deleteDirectoryImpl(Path path) throws IOException {
    Files.walkFileTree(path, DeleteRecursivelyFileVisitor.INSTANCE);
}

From source file:de.hybris.platform.media.storage.impl.MediaCacheRecreatorTest.java

private void cleanCacheFolder(final String folderName) throws IOException {
    Files.walkFileTree(Paths.get(System.getProperty("java.io.tmpdir"), folderName),
            new SimpleFileVisitor<Path>() {
                @Override/*w w  w.j a va  2  s  .c  o m*/
                public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                        throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(final Path file, final IOException exc)
                        throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }
            });
}

From source file:it.infn.ct.futuregateway.apiserver.storage.LocalStorage.java

@Override
public final void removeAllFiles(final RESOURCE res, final String id) throws IOException {
    java.nio.file.Path filePath = Paths.get(path, res.name().toLowerCase(), id);
    if (Files.notExists(filePath)) {
        return;//  w  w  w  .  j av a 2 s.com
    }
    if (Files.isDirectory(filePath)) {
        Files.walkFileTree(filePath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult postVisitDirectory(final Path dir, final IOException exc)
                    throws IOException {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                    throws IOException {
                Files.delete(file);
                return FileVisitResult.CONTINUE;
            }
        });
    }
    Files.delete(filePath);
}

From source file:org.apdplat.superword.tools.WordClassifier.java

public static void parseDir(String dir) {
    LOGGER.info("?" + dir);
    try {//from w ww  . jav a2s  . c o  m
        Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                parseFile(file.toFile().getAbsolutePath());
                return FileVisitResult.CONTINUE;
            }

        });
    } catch (IOException e) {
        LOGGER.error("?", e);
    }
}

From source file:org.sonar.core.util.FileUtils.java

private static void deleteDirectoryImpl(Path path) throws IOException {
    requireNonNull(path, DIRECTORY_CAN_NOT_BE_NULL);
    File file = path.toFile();/*w  w w . j a  v  a  2  s .  com*/
    if (!file.exists()) {
        return;
    }

    checkIO(!Files.isSymbolicLink(path), "Directory '%s' is a symbolic link", path);
    checkIO(!file.isFile(), "Directory '%s' is a file", path);

    Files.walkFileTree(path, DeleteRecursivelyFileVisitor.INSTANCE);

    checkIO(!file.exists(), "Unable to delete directory '%s'", path);
}

From source file:org.talend.dataprep.cache.file.FileSystemContentCacheJanitor.java

/**
 * A clean up process that starts a minute after the previous ended.
 *//*  w  ww .  ja  v  a2  s .co  m*/
@Scheduled(fixedDelay = 60000)
public void janitor() {
    if (!Paths.get(location).toFile().exists()) {
        LOGGER.debug("No cache content to clean.");
        return;
    }
    final long start = System.currentTimeMillis();
    final AtomicLong deletedCount = new AtomicLong();
    final AtomicLong totalCount = new AtomicLong();
    LOGGER.debug("Janitor process started @ {}.", start);
    try {
        final BiConsumer<Path, String> deleteOld = (file, suffix) -> {
            try {
                final long time = Long.parseLong(suffix);
                if (time < start) {
                    try {
                        Files.delete(file);
                        deletedCount.incrementAndGet();
                    } catch (NoSuchFileException e) {
                        LOGGER.debug("Ignored delete issue for '{}'.", file.getFileName(), e);
                    } catch (IOException e) {
                        LOGGER.warn("Unable to delete '{}'.", file.getFileName());
                        LOGGER.debug("Unable to delete '{}'.", file.getFileName(), e);
                    }
                }
            } catch (NumberFormatException e) {
                LOGGER.debug("Ignore file '{}'", file);
            }
            totalCount.incrementAndGet();
        };
        Files.walkFileTree(Paths.get(location), new FileSystemVisitor(deleteOld));
    } catch (IOException e) {
        LOGGER.error("Unable to clean up cache", e);
    }
    LOGGER.debug("Janitor process ended @ {} ({}/{} files successfully deleted).", System.currentTimeMillis(),
            deletedCount, totalCount);
}