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:de.fatalix.book.importer.CalibriImporter.java

public static void processBooks(Path root, String solrURL, String solrCore, final int batchSize)
        throws IOException, SolrServerException {
    final SolrServer solrServer = SolrHandler.createConnection(solrURL, solrCore);
    final List<BookEntry> bookEntries = new ArrayList<>();
    Files.walkFileTree(root, new SimpleFileVisitor<Path>() {

        @Override//  w w w . j a  v a2s . c o  m
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            if (dir.toString().contains("__MACOSX")) {
                return FileVisitResult.SKIP_SUBTREE;
            }
            try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(dir)) {
                BookEntry bookEntry = new BookEntry().setUploader("admin");
                for (Path path : directoryStream) {
                    if (!Files.isDirectory(path)) {
                        if (path.toString().contains(".opf")) {
                            bookEntry = parseOPF(path, bookEntry);
                        }
                        if (path.toString().contains(".mobi")) {
                            bookEntry.setMobi(Files.readAllBytes(path)).setMimeType("MOBI");
                        }
                        if (path.toString().contains(".epub")) {
                            bookEntry.setEpub(Files.readAllBytes(path));
                        }
                        if (path.toString().contains(".jpg")) {
                            bookEntry.setCover(Files.readAllBytes(path));
                            ByteArrayOutputStream output = new ByteArrayOutputStream();
                            Thumbnails.of(new ByteArrayInputStream(bookEntry.getCover())).size(130, 200)
                                    .toOutputStream(output);
                            bookEntry.setThumbnail(output.toByteArray());
                            bookEntry.setThumbnailGenerated("done");
                        }
                    }
                }
                if (bookEntry.getMobi() != null || bookEntry.getEpub() != null) {
                    bookEntries.add(bookEntry);
                    if (bookEntries.size() > batchSize) {
                        System.out.println("Adding " + bookEntries.size() + " Books...");
                        try {
                            SolrHandler.addBeans(solrServer, bookEntries);
                        } catch (SolrServerException ex) {
                            System.out.println(ex.getMessage());
                            ex.printStackTrace();
                        }
                        bookEntries.clear();
                    }
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return super.preVisitDirectory(dir, attrs);
        }
    });
}

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

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

                @Override/*from  w ww  .  j ava2s. c  o m*/
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    LOGGER.info("?" + file);
                    // ?
                    Path temp = Paths.get("target/java-source-code.txt");
                    Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING);
                    Map<String, AtomicInteger> r = parseFile(temp.toFile().getAbsolutePath());
                    r.keySet().forEach(k -> {
                        data.putIfAbsent(k, new AtomicInteger());
                        data.get(k).addAndGet(r.get(k).get());
                    });
                    r.clear();
                    return FileVisitResult.CONTINUE;
                }

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

From source file:org.neo4j.io.fs.FileUtils.java

public static void deletePathRecursively(Path path) throws IOException {
    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override//from  w ww. java2s  .  c  om
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            deleteFileWithRetries(file, 0);
            return FileVisitResult.CONTINUE;
        }

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

From source file:desktopsearch.WatchDir.java

/**
 * Register the given directory, and all its sub-directories, with the
 * WatchService./*from  ww  w .ja  v a2s .c om*/
 */
private void registerAll(final Path start) {
    // register directory and sub-directories
    try {
        Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                register(dir);
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:fi.hsl.parkandride.ExportQTypes.java

private static void deleteOldQTypes(Path packageDir) throws IOException {
    Files.walkFileTree(packageDir, new SimpleFileVisitor<Path>() {
        @Override// w  w  w.j  a  v  a2s.  c  o m
        public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
            if (path.getFileName().toString().startsWith(NAME_PREFIX)) {
                Files.delete(path);
            }
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:org.apache.openaz.xacml.pdp.test.conformance.ConformanceTestSet.java

public static ConformanceTestSet loadDirectory(File fileDir) throws IOException {
    final Map<String, ConformanceTest> mapConformanceTests = new HashMap<String, ConformanceTest>();

    Files.walkFileTree(fileDir.toPath(), new FileVisitor<Path>() {
        @Override//from  w w  w.j a  v a  2s  .  c  om
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            logger.info("Scanning directory " + dir.getFileName());
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            File fileVisited = file.toFile();
            String fileName = fileVisited.getName();
            if (fileName.endsWith(".xml") || fileName.endsWith(".properties")) {
                String testName = getTestName(fileVisited);
                if (testName != null) {
                    ConformanceTest conformanceTest = mapConformanceTests.get(testName);
                    if (conformanceTest == null) {
                        logger.info("Added test " + testName);
                        conformanceTest = new ConformanceTest(testName);
                        mapConformanceTests.put(testName, conformanceTest);
                    }
                    if (fileName.endsWith("Policy.xml")) {
                        conformanceTest.getRepository().addRootPolicy(fileVisited);
                    } else if (fileName.endsWith("Repository.properties")) {
                        conformanceTest.getRepository().load(fileVisited);
                    } else if (fileName.endsWith("Request.xml")) {
                        conformanceTest.setRequest(fileVisited);
                    } else if (fileName.endsWith("Response.xml")) {
                        conformanceTest.setResponse(fileVisited);
                    }
                }
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
            logger.warn("Skipped " + file.getFileName());
            return FileVisitResult.CONTINUE;
        }

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

    /*
     * Sort the keyset and pull out the tests that have the required components
     */
    List<String> listTestNames = new ArrayList<String>();
    listTestNames.addAll(mapConformanceTests.keySet());
    Collections.sort(listTestNames);

    ConformanceTestSet conformanceTestSet = new ConformanceTestSet();
    Iterator<String> iterTestNames = listTestNames.iterator();
    while (iterTestNames.hasNext()) {
        ConformanceTest conformanceTest = mapConformanceTests.get(iterTestNames.next());
        if (conformanceTest.isComplete()) {
            conformanceTestSet.addConformanceTest(conformanceTest);
            logger.debug("Added conformance test " + conformanceTest.getTestName());
        } else {
            logger.warn("Incomplete conformance test " + conformanceTest.getTestName());
        }
    }

    return conformanceTestSet;

}

From source file:io.crate.testing.Utils.java

public static void deletePath(Path path) throws IOException {
    Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
        @Override//from w  ww  .  j  a  va2  s.c  o m
        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;
        }

    });
}

From source file:internal.diff.fs.service.FileSystemDirectoryMetadataServiceImpl.java

@Override
public DirectoryMetadata getMetadata(String path) {

    Path startPath = Paths.get(path);
    DirectoryMetadataBuildingFileVisitor visitor = new DirectoryMetadataBuildingFileVisitor();

    try {/*from w w w  .  j  a  v  a  2 s. c  om*/
        Files.walkFileTree(startPath, visitor);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return visitor.getRootDirectory();
}

From source file:com.netease.hearttouch.hthotfix.patch.PatchGeneratorTransformExecutor.java

public void transformDirectory(File inputFile, File outputFile) throws IOException {

    Path inputDir = inputFile.toPath();
    Path outputDir = outputFile.toPath();

    if (!Files.isDirectory(inputDir)) {
        return;/*w  ww .j a  v  a 2 s. c o  m*/
    }
    final OutputDirectory outputDirectory = new OutputDirectory(outputDir);
    Files.walkFileTree(inputDir, new ClasspathVisitor() {
        @Override
        protected void visitClass(Path path, byte[] bytecode) throws IOException {
            ClassReader cr = new ClassReader(bytecode);
            String className = cr.getClassName();

            if (extension.getGeneratePatch()) {
                if (hashFileParser == null) {
                    project.getLogger().error("hashFileParser is null,do you set  generatePath true?");
                }

                if ((hashFileParser != null) && (hashFileParser.isChanged(className, bytecode))) {
                    project.getLogger().error("has change classname,\t" + className);

                    ResourceDiffChecker.checkClass(project, className);
                    patchJarHelper.writeClassToDirectory(className, hackInjector.inject(className, bytecode));
                    refScanInstrument.addPatchClassName(className, hackInjector.getLastSuperName());

                }
            }
            outputDirectory.writeClass(className, bytecode);
        }

        @Override
        protected void visitResource(Path relativePath, byte[] content) throws IOException {
            outputDirectory.writeFile(relativePath, content);

        }
    });
}

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

public static Map<String, AtomicInteger> parseDir(String dir) {
    Map<String, AtomicInteger> data = new HashMap<>();
    LOGGER.info("?" + dir);
    try {/*from  ww  w .  j av  a 2  s.  c  o m*/
        Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Map<String, AtomicInteger> rs = parseFile(file.toFile().getAbsolutePath());
                rs.keySet().forEach(k -> {
                    data.putIfAbsent(k, new AtomicInteger());
                    data.get(k).addAndGet(rs.get(k).get());
                });
                return FileVisitResult.CONTINUE;
            }

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