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.egov.infra.filestore.service.impl.LocalDiskFileStoreServiceTest.java

@AfterClass
public static void afterTest() throws IOException {
    Files.deleteIfExists(tempFilePath);
    Path storePath = Paths.get(System.getProperty("user.home") + File.separator + "testfilestore");
    try {//from  w  ww  . j  a  v a  2s  .c om
        Files.walkFileTree(storePath, 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 {
                if (exc == null) {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                } else {
                    throw exc;
                }
            }

        });
    } catch (IOException e) {

    }
}

From source file:com.collaborne.jsonschema.generator.pojo.PojoGeneratorSmokeTest.java

@After
public void tearDown() throws IOException {
    // Dump the contents of the file system
    Path dumpStart = fs.getPath("/");
    Files.walkFileTree(dumpStart, new SimpleFileVisitor<Path>() {
        @Override/*from  ww  w . j ava  2s.  c  o m*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            System.out.println("> " + file);
            System.out.println(new String(Files.readAllBytes(file), StandardCharsets.UTF_8));

            // Copy the file if wanted
            if (DUMP_DIRECTORY != null) {
                Path dumpTarget = Paths.get(DUMP_DIRECTORY, name.getMethodName());
                Path target = dumpTarget.resolve(dumpStart.relativize(file).toString());
                Files.createDirectories(target.getParent());
                Files.copy(file, target, StandardCopyOption.REPLACE_EXISTING);
            }
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:com.marklogic.hub.RestAssetLoader.java

/**
 * For walking one or many paths and loading modules in each of them.
 *///from   ww  w .j  a  va2s. co  m
public Set<File> loadAssetsViaREST(String... paths) {
    currentTransaction = client.openTransaction();
    filesLoaded = new HashSet<>();
    try {
        for (String path : paths) {
            if (logger.isDebugEnabled()) {
                logger.debug(format("Loading assets from path: %s", path));
            }
            this.currentAssetPath = Paths.get(path);
            this.currentRootPath = this.currentAssetPath;
            try {
                Files.walkFileTree(this.currentAssetPath, this);
            } catch (IOException ie) {
                throw new RuntimeException(format("Error while walking assets file tree: %s", ie.getMessage()),
                        ie);
            }
        }
        currentTransaction.commit();
    } catch (Exception e) {
        currentTransaction.rollback();
    }
    return filesLoaded;
}

From source file:it.polimi.diceH2020.SPACE4CloudWS.fileManagement.FileUtility.java

public boolean destroyDir(@NotNull File path) throws IOException {
    Path directory = path.toPath();

    @Getter//from   w  w  w.java2 s . c om
    @Setter
    class BooleanWrapper {
        boolean deleted;
    }
    BooleanWrapper status = new BooleanWrapper();

    Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            status.setDeleted(policy.delete(file.toFile()));
            return FileVisitResult.CONTINUE;
        }

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

    return status.isDeleted();
}

From source file:de.ingrid.interfaces.csw.tools.FileUtils.java

/**
 * Delete a file or directory specified by a {@link Path}. This method uses
 * the new {@link Files} API and allows to specify a regular expression to
 * remove only files that match that expression.
 * /*from  w w  w.  j a va  2s  .  c  o m*/
 * @param path
 * @param pattern
 * @throws IOException
 */
public static void deleteRecursive(Path path, final String pattern) throws IOException {

    final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("regex:" + pattern);

    if (!Files.exists(path))
        return;

    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (pattern != null && matcher.matches(file.getFileName())) {
                Files.delete(file);
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            // try to delete the file anyway, even if its attributes
            // could not be read, since delete-only access is
            // theoretically possible
            if (pattern != null && matcher.matches(file.getFileName())) {
                Files.delete(file);
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            if (exc == null) {
                if (matcher.matches(dir.getFileName())) {
                    if (dir.toFile().list().length > 0) {
                        // remove even if not empty
                        FileUtils.deleteRecursive(dir);
                    } else {
                        Files.delete(dir);
                    }
                }
                return FileVisitResult.CONTINUE;
            } else {
                // directory iteration failed; propagate exception
                throw exc;
            }
        }

    });
}

From source file:org.sonar.api.utils.internal.DefaultTempFolder.java

public void clean() {
    try {/*  w w  w . ja va2  s  .c  om*/
        Files.walkFileTree(tempDir.toPath(), DeleteRecursivelyFileVisitor.INSTANCE);
    } catch (IOException e) {
        LOG.trace("Failed to delete temp folder", e);
    }
}

From source file:org.bonitasoft.console.common.server.page.CustomPageDependenciesResolver.java

private Map<String, byte[]> loadLibraries(final File customPageLibDirectory) {
    final Map<String, byte[]> result = new HashMap<String, byte[]>();
    try {//from   ww  w  .  j ava2s .  com
        Files.walkFileTree(customPageLibDirectory.toPath(), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                    throws IOException {
                final File currentFile = file.toFile();
                result.put(currentFile.getName(), readFileToByteArray(currentFile));
                return super.visitFile(file, attrs);
            }

        });
    } catch (final IOException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }
    return result;
}

From source file:client.tools.ClientRecovery.java

/**
 * Starts the recovery process./*  w  ww .j  a v a  2s.  co  m*/
 * 
 * @return <code>true</code>, if this recovery was successfully executed.
 *         Otherwise, <code>false</code>.
 */
public boolean execute() {
    try {
        if (Files.isHidden(syncPath) || !syncPath.startsWith(filesPath)) {
            Files.walkFileTree(syncPath, new DeleteTempFileVisitor(syncPath));
        }
        Files.walkFileTree(filesPath, new DeleteTempFileVisitor(syncPath));
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:br.com.uol.runas.classloader.JarClassLoader.java

private void addUrlsFromDir(URL url) throws IOException, URISyntaxException {
    addURL(url);/* w w w. j  a va  2  s .c  o m*/

    Files.walkFileTree(Paths.get(url.toURI()), new FileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            addURL(dir.toUri().toURL());
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            addURL(file.toUri().toURL());
            return FileVisitResult.CONTINUE;
        }

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

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

From source file:com.ignorelist.kassandra.steam.scraper.PathResolver.java

public Set<Path> findSharedConfig() throws IOException {
    Path base = findSteamBase().resolve("steam").resolve("userdata");
    final Set<Path> paths = new HashSet<>();
    Files.walkFileTree(base, new SimpleFileVisitor<Path>() {
        @Override//from  w  ww  . ja  v  a 2 s. com
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if ("sharedconfig.vdf".equals(file.getFileName().toString())) {
                paths.add(file);
            }
            return super.visitFile(file, attrs);
        }

    });
    if (paths.isEmpty()) {
        throw new IllegalStateException("can't find sharedconfig.vdf");
    }
    return paths;
}