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.apdplat.superword.tools.WordClassifier.java

public static void parseZip(String zipFile) {
    LOGGER.info("?ZIP" + zipFile);
    try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), WordClassifier.class.getClassLoader())) {
        for (Path path : fs.getRootDirectories()) {
            LOGGER.info("?" + path);
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

                @Override/*from   ww w .  j  av  a 2 s.com*/
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    LOGGER.info("?" + file);
                    // ?
                    Path temp = Paths.get("target/origin-html-temp.txt");
                    Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING);
                    parseFile(temp.toFile().getAbsolutePath());
                    return FileVisitResult.CONTINUE;
                }

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

From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalResourceServiceCopyWebdavDirectoryTestExecutionListener.java

private void cleanDirectory(Path directory) {
    if (!Files.isDirectory(directory)) {
        return;/*from w ww. ja v  a  2 s.c  o m*/
    }

    try {
        log.debug("Remove all Contents of Directory {}", directory.toAbsolutePath().toString());
        Files.walkFileTree(directory, 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 (!Files.isSameFile(dir, directory)) {
                    Files.delete(dir);
                }
                return FileVisitResult.CONTINUE;
            }
        });
        Files.delete(directory);
    } catch (IOException e) {
        throw new RuntimeException(
                String.format("IOException while cleaning Directory %s", directory.toAbsolutePath().toString()),
                e);
    }
}

From source file:org.nuxeo.ecm.webengine.gwt.GwtResolver.java

protected File install(URI location) throws IOException {
    if ("jar".equals(location.getScheme())) {
        Map<String, Object> env = Collections.emptyMap();
        try (FileSystem fileSystem = FileSystems.newFileSystem(location, env,
                this.getClass().getClassLoader());) {
            Path path = Paths.get(location);
            try {
                // it's a directory
                return path.toFile();
            } catch (UnsupportedOperationException cause) {
                // it's a jar, we should install content
            }//  w  w  w .java  2 s .  co  m
            Files.walkFileTree(path, new TreeImporter(path, GWT_ROOT.toPath()));
            return GWT_ROOT;
        }
    }
    return Paths.get(location).toFile();
}

From source file:cz.muni.fi.mir.services.FileDirectoryService.java

/**
 * Method used for obtaining SourceDocuments out of given path including
 * subdirectories matching fileName. Check out {@link MathFileVisitor} class
 * which is used for walking, to see the structure of fileName. Method
 * ensures following out of path that has been matched:
 * <ul>//from   w  ww.j a  v  a 2 s .co  m
 * <li>creates formula object</li>
 * <li>as output is set empty ArrayList</li>
 * <li>as content content of given file is set</li>
 * <li>current time is set as insert time</li>
 * <li>result is added into resultList</li>
 * <li>sets logged user as creator</li>
 * </ul>
 * If any error occurs during the reading of file exception is
 * <b>suppressed</b> and logged with error level.
 *
 * @param path root path in which are desired files
 * @param filter regex value used for file matching. If empty default based
 * on {@link #MATCH_PATTERN} is set.
 * @return Formulas found in given folder matched against filter.
 * @throws FileNotFoundException if root path does not exist
 */
public List<Formula> exploreDirectory(Path path, String filter) throws FileNotFoundException {
    if (!Files.exists(path)) {
        throw new FileNotFoundException("Root directory " + path + " not found.");
    }
    if (Tools.getInstance().stringIsEmpty(filter)) {
        filter = MATCH_PATTERN;
    }

    MathFileVisitor mfv = new MathFileVisitor(filter, MathFileVisitor.MathFileVisitorType.GLOB);

    try {
        Files.walkFileTree(path, mfv);
    } catch (IOException ex) {
        logger.error(ex);
    }

    List<Formula> result = new ArrayList<>(mfv.done().size());
    User u = securityContext.getLoggedEntityUser();
    for (Path p : mfv.done()) {
        Formula f = EntityFactory.createFormula();
        f.setOutputs(new ArrayList<CanonicOutput>());
        InputStream is = null;
        try {
            is = Files.newInputStream(p);
            f.setXml(IOUtils.toString(is));
            f.setInsertTime(DateTime.now());
            f.setUser(u);
            result.add(f);
        } catch (IOException ex) {
            logger.error(ex);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ex) {
                    logger.fatal(ex);
                }
            }
        }
    }

    return result;
}

From source file:ch.devmine.javaparser.Main.java

private static void parseAsDirectory(Project project, HashMap<String, Package> packs, List<Language> languages,
        Language language, String arg) {
    File repoRoot = new File(arg);
    Path repoPath = repoRoot.toPath();

    FilesWalker fileWalker = new FilesWalker();
    try {/*from  w ww . j  a  va  2 s. co m*/
        Files.walkFileTree(repoPath, fileWalker);
    } catch (IOException ex) {
        Log.e(TAG, ex.getMessage());
    }

    String path = repoPath.toString();
    String name = path.substring(path.lastIndexOf("/") + 1);
    project.setName(name);

    for (String dir : fileWalker.getDirectories()) {
        dir = dir.replaceAll("\n", "");
        if (FileTypeFinder.search(dir, ".java")) {
            Package pack = new Package();
            String packName = dir.substring(dir.lastIndexOf("/") + 1);
            pack.setName(packName);
            pack.setPath(dir);
            packs.put(packName, pack);
        }
    }

    List<String> javaFiles = FileWalkerUtils.extractJavaFiles(fileWalker.getRegularFiles());
    for (String javaFile : javaFiles) {
        try {
            Parser parser = new Parser(javaFile, null);
            SourceFile sourceFile = new SourceFile();
            String packName = FileWalkerUtils.extractFolderName(javaFile);
            parseAndFillSourceFile(parser, sourceFile, javaFile, language, packs, packName);
        } catch (FileNotFoundException ex) {
            Log.e(TAG, ex.getMessage());
        }
    }

}

From source file:ru.histone.staticrender.StaticRenderTest.java

private void assertFilesEqualsInDirs(final Path expectedDir, final Path actualDir) throws IOException {
    final Set<String> notFoundInResult = new TreeSet();
    final Set<String> unexpectedFilesInResult = new TreeSet();
    final Set<String> notIdenticalFiles = new TreeSet();

    FileVisitor<Path> filesVisitor1 = new SimpleFileVisitor<Path>() {
        @Override//from ww w  .j  av a2  s .c om
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Path relativePath = expectedDir.relativize(file);

            String expected = new String(Files.readAllBytes(expectedDir.resolve(relativePath)), "UTF-8");
            String actual = null;
            final Path actualFile = actualDir.resolve(relativePath);
            if (actualFile.toFile().exists()) {
                actual = new String(Files.readAllBytes(actualFile), "UTF-8");
                if (!expected.equals(actual)) {
                    notIdenticalFiles.add(relativePath.toString());
                }
            } else {
                notFoundInResult.add(relativePath.toString());
            }

            return FileVisitResult.CONTINUE;
        }
    };

    FileVisitor<Path> filesVisitor2 = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Path relativePath = actualDir.relativize(file);

            String expected = new String(Files.readAllBytes(actualDir.resolve(relativePath)), "UTF-8");
            String actual = null;
            final Path actualFile = expectedDir.resolve(relativePath);
            if (actualFile.toFile().exists()) {
                actual = new String(Files.readAllBytes(actualFile), "UTF-8");
                if (!expected.equals(actual)) {
                    notIdenticalFiles.add(relativePath.toString());
                }
            } else {
                unexpectedFilesInResult.add(relativePath.toString());
            }

            return FileVisitResult.CONTINUE;
        }
    };

    Files.walkFileTree(expectedDir, filesVisitor1);
    Files.walkFileTree(actualDir, filesVisitor2);

    StringBuilder err = new StringBuilder();
    if (notFoundInResult.size() > 0) {
        err.append("Files not found in result: " + Joiner.on(", ").join(notFoundInResult)).append("\n");
    }
    if (unexpectedFilesInResult.size() > 0) {
        err.append("Unexpected files found in result: " + Joiner.on(", ").join(unexpectedFilesInResult))
                .append("\n");
    }
    if (notIdenticalFiles.size() > 0) {
        err.append("Files differ in expected and in result: " + Joiner.on(", ").join(notIdenticalFiles))
                .append("\n");
    }

    if (err.length() > 0) {
        fail("Folders diff fail:\n" + err.toString());
    }
}

From source file:com.garyclayburg.filesystem.WatchDir.java

/**
 * Register the given directory, and all its sub-directories, with the
 * WatchService.//from ww w .jav a  2  s.com
 */
private void registerAll(final Path start) throws IOException {
    // register directory and sub-directories
    Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            register(dir);
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:org.openhab.tools.analysis.checkstyle.PackageExportsNameCheck.java

/**
 * Filter and return the packages from the source directory. Only not excluded packages will be returned.
 *
 * @param sourcePath - The full path of the source directory
 * @return {@link Set } of {@link String }s with the package names.
 * @throws IOException if an I/O error is thrown while visiting files
 */// w ww  .ja v  a  2  s.  c om
private Set<String> getFilteredPackagesFromSourceDirectory(Path sourcePath) throws IOException {
    Set<String> packages = new HashSet<>();
    // No symbolic links are expected in the source directory
    if (Files.exists(sourcePath, LinkOption.NOFOLLOW_LINKS)) {
        Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) {
                Path packageRelativePath = sourcePath.relativize(path.getParent());
                String packageName = packageRelativePath.toString()
                        .replaceAll(Matcher.quoteReplacement(File.separator), ".");

                if (!isExcluded(packageName)) {
                    packages.add(packageName);
                }
                return FileVisitResult.CONTINUE;
            }
        });
    }

    return packages;
}

From source file:company.gonapps.loghut.utils.FileUtils.java

public List<Path> scan(Path path) throws IOException {
    paths = new LinkedList<>();
    Files.walkFileTree(path, this);
    return paths;
}

From source file:org.wte4j.examples.showcase.server.hsql.ShowCaseDbInitializerTest.java

private void deleteDirectory(Path path) throws IOException {

    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override/*from  ww  w .j ava2  s  . c o  m*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.deleteIfExists(file);
            return super.visitFile(file, attrs);
        }
    });
    Files.deleteIfExists(path);

}