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:nl.salp.warcraft4j.config.PropertyWarcraft4jConfigTest.java

private static void delete(Path directory) throws Exception {
    Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
        @Override/*from  www.jav  a  2 s .  c om*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Files.delete(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult postVisitDirectory(Path dir, IOException e) throws IOException {
            if (e == null) {
                Files.delete(dir);
                return FileVisitResult.CONTINUE;
            } else {
                throw e;
            }
        }
    });
}

From source file:io.gravitee.maven.plugins.json.schema.generator.util.ClassFinder.java

/**
 * Find class Paths from the given root Path that match the given list of globs.
 *
 * @param root  the root Path from which start searching
 * @param globs the glob list to taking into account during path matching
 * @return a list of Paths that match the given list of globs from the root Path
 * @throws IOException if an I/O occurs//  w w  w.j ava 2s .com
 */
private static List<Path> findClassPaths(Path root, Globs globs) throws IOException {
    List<Path> matchedPaths = new ArrayList<>();
    Files.walkFileTree(root.normalize(), new GlobsMatchingClassFileVisitor(globs, matchedPaths));
    return matchedPaths;
}

From source file:org.apdplat.superword.extract.PhraseExtractor.java

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

                @Override/*from ww  w.j  a  v  a 2 s. c o  m*/
                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);
                    data.addAll(parseFile(temp.toFile().getAbsolutePath()));
                    return FileVisitResult.CONTINUE;
                }

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

From source file:net.minecrell.quartz.launch.mappings.MappingsLoader.java

public static Mappings load(Logger logger) throws IOException {
    URI source;//www. ja  v  a  2s  .  c om
    try {
        source = requireNonNull(Mapping.class.getProtectionDomain().getCodeSource(),
                "Unable to find class source").getLocation().toURI();
    } catch (URISyntaxException e) {
        throw new IOException("Failed to find class source", e);
    }

    Path location = Paths.get(source);
    logger.debug("Mappings location: {}", location);

    List<ClassNode> mappingClasses = new ArrayList<>();

    // Load the classes from the source
    if (Files.isDirectory(location)) {
        // We're probably in development environment or something similar
        // Search for the class files
        Files.walkFileTree(location.resolve(PACKAGE), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.getFileName().toString().endsWith(".class")) {
                    try (InputStream in = Files.newInputStream(file)) {
                        ClassNode classNode = MappingsParser.loadClassStructure(in);
                        mappingClasses.add(classNode);
                    }
                }

                return FileVisitResult.CONTINUE;
            }
        });
    } else {
        // Go through the JAR file
        try (ZipFile zip = new ZipFile(location.toFile())) {
            Enumeration<? extends ZipEntry> entries = zip.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                String name = StringUtils.removeStart(entry.getName(), MAPPINGS_DIR);
                if (entry.isDirectory() || !name.endsWith(".class") || !name.startsWith(PACKAGE_PREFIX)) {
                    continue;
                }

                // Ok, we found something
                try (InputStream in = zip.getInputStream(entry)) {
                    ClassNode classNode = MappingsParser.loadClassStructure(in);
                    mappingClasses.add(classNode);
                }
            }
        }
    }

    return new Mappings(mappingClasses);
}

From source file:com.ejisto.util.IOUtils.java

private static void copyDirContent(Path srcDir, Path targetDir, FileMatcher matcher,
        final String copiedFilesPrefix, CopyType copyType) {
    try {/*from  w  ww  .  j a  v  a 2  s  .c  om*/
        Files.walkFileTree(srcDir, new ConditionMatchingCopyFileVisitor(
                new CopyOptions(srcDir, targetDir, matcher, copiedFilesPrefix, copyType)));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apdplat.superword.extract.DefinitionExtractor.java

public static Set<Word> parseZip(String zipFile) {
    Set<Word> data = new HashSet<>();
    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// w w  w. j ava  2s.co  m
                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);
                    data.addAll(parseFile(temp.toFile().getAbsolutePath()));
                    return FileVisitResult.CONTINUE;
                }

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

From source file:ps3joiner.Main.java

/**
 * @return a MultiMap where each key is the Path to a whole file, and the values are the partial files, sorted by name
 *///from  www  .j a v a2  s  .  c  om
public static ImmutableMultimap<Path, Path> findFilesToJoin(final Path path) throws IOException {
    final Map<Path, Path> splitToWholeFileMapping = new HashMap<>();

    final SplitFilesVisitor visitor = new SplitFilesVisitor();
    Files.walkFileTree(path, visitor);
    final List<Path> foundPaths = visitor.foundPaths();
    for (final Path foundPath : foundPaths) {
        final Path originalFilePath = findOriginalFileFromSplitFile(foundPath);
        splitToWholeFileMapping.put(foundPath, originalFilePath);
    }

    final Multimap<Path, Path> multimap = TreeMultimap.create();
    for (final Entry<Path, Path> entry : splitToWholeFileMapping.entrySet()) {
        final Path splitFilePath = entry.getKey();
        final Path wholeFilePath = entry.getValue();

        multimap.put(wholeFilePath, splitFilePath);
    }
    return ImmutableMultimap.copyOf(multimap);
}

From source file:com.ilscipio.scipio.common.FileListener.java

/**
 *  Start a file listener (WatchService) and run a service of a given name and writes the result to the database
 *  Can be used to implements EECAs to auto-update information based on file changes
 **/// w  w  w . j  a v a2  s  .  com
public static void startFileListener(String name, String location) {

    try {
        if (UtilValidate.isNotEmpty(name) && UtilValidate.isNotEmpty(location)) {

            if (getThreadByName(name) != null) {
                Debug.logInfo("Filelistener " + name + " already started. Skipping...", module);
            } else {
                URL resLocation = UtilURL.fromResource(location);
                Path folderLocation = Paths.get(resLocation.toURI());
                if (folderLocation == null) {
                    throw new UnsupportedOperationException("Directory not found");
                }

                final WatchService folderWatcher = folderLocation.getFileSystem().newWatchService();
                // register all subfolders
                Files.walkFileTree(folderLocation, new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        dir.register(folderWatcher, StandardWatchEventKinds.ENTRY_CREATE,
                                StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
                        return FileVisitResult.CONTINUE;
                    }
                });

                // start the file watcher thread below
                ScipioWatchQueueReader fileListener = new ScipioWatchQueueReader(folderWatcher, name, location);
                ScheduledExecutorService executor = ExecutionPool.getScheduledExecutor(
                        FILE_LISTENER_THREAD_GROUP, "filelistener-startup",
                        Runtime.getRuntime().availableProcessors(), 0, true);
                try {
                    executor.submit(fileListener, name);
                } finally {
                    executor.shutdown();
                }
                Debug.logInfo("Starting FileListener thread for " + name, module);
            }
        }
    } catch (Exception e) {
        Debug.logError("Could not start FileListener " + name + " for " + location + "\n" + e, module);

    }
}

From source file:br.com.softplan.jsversioning.process.WebFilesProcessor.java

public void process() {
    this.log.debug("Start to walk the file tree of path on " + this.webFilesDirectory);
    try {/*from   w w  w .j a v  a2 s .c o  m*/
        Files.walkFileTree(this.webFilesDirectory, new WebFilesVisitor());
    } catch (Exception e) {
        throw new IllegalStateException("Error processing files: ", e);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.discourse.pdtbparser.PDTBParserWrapper.java

public PDTBParserWrapper() throws IOException {
    tempDirectory = Files.createTempDirectory("temp_pdtb");

    //        FileUtils.copyFileToDirectory();
    File tempDir = tempDirectory.toFile();

    File tmpFile = File.createTempFile("tmp_pdtb", ".zip");

    InputStream stream = getClass().getClassLoader().getResourceAsStream("pdtb-parser-v120415.zip");
    FileUtils.copyInputStreamToFile(stream, tmpFile);

    ZipFile zipFile;/* ww  w.j  a  v  a 2s  .co  m*/
    try {
        zipFile = new ZipFile(tmpFile);
        zipFile.extractAll(tempDir.getAbsolutePath());
    } catch (ZipException e) {
        throw new IOException(e);
    }

    // delete temp file
    FileUtils.forceDelete(tmpFile);

    String folderPrefix = "/pdtb-parser-v120415/src";
    String srcDir = tempDir.getCanonicalPath() + folderPrefix;

    // copy rewritten rb files
    copyFiles(new File(srcDir), "article.rb", "parser.rb");

    Files.walkFileTree(tempDirectory, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Set<PosixFilePermission> permissions = new HashSet<>();
            permissions.add(PosixFilePermission.OWNER_EXECUTE);
            permissions.add(PosixFilePermission.GROUP_EXECUTE);
            permissions.add(PosixFilePermission.OTHERS_EXECUTE);
            permissions.add(PosixFilePermission.OWNER_READ);
            permissions.add(PosixFilePermission.GROUP_READ);
            permissions.add(PosixFilePermission.OTHERS_READ);

            Files.setPosixFilePermissions(file, permissions);

            return super.visitFile(file, attrs);
        }
    });

    parserRubyScript = srcDir + "/parser.rb";

    System.out.println(parserRubyScript);
}