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.alexkamp.sandbox.ChrootSandboxFactory.java

@Override
public void deleteSandbox(final SandboxData sandbox) {
    File copyDir = sandbox.getBaseDir();

    try {/*  w w w . ja v  a 2s. co  m*/
        final AtomicInteger depth = new AtomicInteger(0);
        Files.walkFileTree(copyDir.toPath(), new FileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes basicFileAttributes)
                    throws IOException {
                int d = depth.getAndIncrement();

                // see whether the mounts are gone
                if (1 == d) {
                    for (Mount m : sandbox) {
                        if (path.endsWith(m.getMountPoint().substring(1))) {
                            if (0 != path.toFile().listFiles().length) {
                                throw new IllegalArgumentException(
                                        path.getFileName() + " has not been unmounted.");
                            }
                        }
                    }
                }

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes)
                    throws IOException {
                Files.delete(path);
                return FileVisitResult.CONTINUE;
            }

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

            @Override
            public FileVisitResult postVisitDirectory(Path path, IOException e) throws IOException {
                Files.delete(path);
                depth.decrementAndGet();
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        throw new SandboxException(e);
    }
}

From source file:org.sonarsource.commandlinezip.ZipUtils7.java

public static void smartReportZip(final Path srcDir, Path zip) throws IOException {
    try (final OutputStream out = FileUtils.openOutputStream(zip.toFile());
            final ZipOutputStream zout = new ZipOutputStream(out)) {
        Files.walkFileTree(srcDir, new SimpleFileVisitor<Path>() {
            @Override//w w w.  ja v a 2s.  c o  m
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                try (InputStream in = new BufferedInputStream(new FileInputStream(file.toFile()))) {
                    String entryName = srcDir.relativize(file).toString();
                    int level = file.toString().endsWith(".pb") ? ZipOutputStream.STORED
                            : Deflater.DEFAULT_COMPRESSION;
                    zout.setLevel(level);
                    ZipEntry entry = new ZipEntry(entryName);
                    zout.putNextEntry(entry);
                    IOUtils.copy(in, zout);
                    zout.closeEntry();
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if (dir.equals(srcDir)) {
                    return FileVisitResult.CONTINUE;
                }

                String entryName = srcDir.relativize(dir).toString();
                ZipEntry entry = new ZipEntry(entryName);
                zout.putNextEntry(entry);
                zout.closeEntry();
                return FileVisitResult.CONTINUE;
            }
        });
    }
}

From source file:io.uploader.drive.util.FileUtils.java

public static Queue<Path> getAllFilesPath(Path srcDir, FileFinderOption option) throws IOException {
    Queue<Path> queue = new ArrayDeque<Path>();
    if (srcDir == null || !Files.isDirectory(srcDir))
        return queue;

    TreePathFinder tpf = new TreePathFinder(queue, option);
    Files.walkFileTree(srcDir, tpf);

    return queue;
}

From source file:org.bonitasoft.platform.configuration.util.FolderComparator.java

public Map<String, File> flattenFolderFiles(File folder) throws IOException {
    Map<String, File> fileMap = new HashMap<>();
    final FlattenFolderVisitor flattenFolderVisitor = new FlattenFolderVisitor(fileMap);
    Files.walkFileTree(folder.toPath(), flattenFolderVisitor);
    return fileMap;
}

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

public static Set<SynonymAntonym> parseZip(String zipFile) {
    Set<SynonymAntonym> 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.  ja  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:io.stallion.dataAccess.file.TomlPersister.java

@Override
public List fetchAll() {
    File target = new File(Settings.instance().getTargetFolder());
    if (!target.isDirectory()) {
        if (getItemController().isWritable()) {
            target.mkdirs();//from  w  ww  .j a  v a2 s .c o  m
        } else {
            throw new ConfigException(String.format(
                    "The TOML bucket %s (path %s) is read-only, but does not exist in the file system. Either create the folder, make it writable, or remove it from the configuration.",
                    getItemController().getBucket(), getBucketFolderPath()));
        }
    }
    TreeVisitor visitor = new TreeVisitor();
    Path folderPath = FileSystems.getDefault().getPath(getBucketFolderPath());
    try {
        Files.walkFileTree(folderPath, visitor);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    List<Object> objects = new ArrayList<>();
    for (Path path : visitor.getPaths()) {
        if (!path.toString().toLowerCase().endsWith(".toml")) {
            continue;
        }
        if (path.toString().contains(".#")) {
            continue;
        }
        Log.fine("Load from toml file " + path);
        if (isManyItemsPerFile()) {
            try {
                Log.finer("Load toml path {0} and items {1}", path.toString(), getItemArrayName());
                String toml = FileUtils.readFileToString(new File(path.toString()), UTF8);
                Toml t = new Toml().read(toml);
                List<HashMap> models = t.getList(getItemArrayName());
                long x = 0;
                for (Map m : models) {
                    x++;
                    T o = getModelClass().newInstance();
                    for (Object key : m.keySet()) {
                        PropertyUtils.setProperty(o, key.toString(), m.get(key));
                    }
                    Log.info("add item {0}", ((MappedModel) o).get("title"));
                    if (empty(o.getId())) {
                        o.setId(x);
                    }
                    handleFetchOne(o);
                    objects.add(o);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            }

        } else {
            objects.add(fetchOne(path.toString()));
        }

    }
    return objects;
}

From source file:server.tools.ServerRecovery.java

/**
 * Starts the recovery process./*ww  w.  jav  a2  s  .co m*/
 * 
 * @return <code>true</code>, if this recovery was successfully executed.
 *         Otherwise, <code>false</code>.
 */
public boolean execute() {
    try {
        Files.walkFileTree(filesPath, new DeleteOrphanVisitor(filesPath));
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:org.jetbrains.webdemo.backend.executor.ExecutorUtils.java

public static ExecutionResult executeCompiledFiles(Map<String, byte[]> files, String mainClass,
        List<Path> kotlinRuntimeJars, String arguments, Path executorsPolicy, boolean isJunit)
        throws Exception {
    Path codeDirectory = null;//from  w w  w . j a  v a2 s.c o  m
    try {
        codeDirectory = storeFilesInTemporaryDirectory(files);
        JavaExecutorBuilder executorBuilder = new JavaExecutorBuilder().enableAssertions().setMemoryLimit(32)
                .enableSecurityManager().setPolicyFile(executorsPolicy).addToClasspath(kotlinRuntimeJars)
                .addToClasspath(jarFiles).addToClasspath(codeDirectory);
        if (isJunit) {
            executorBuilder.addToClasspath(junit);
            executorBuilder.addToClasspath(hamcrest);
            executorBuilder.setMainClass("org.jetbrains.webdemo.executors.JunitExecutor");
            executorBuilder.addArgument(codeDirectory.toString());
        } else {
            executorBuilder.setMainClass("org.jetbrains.webdemo.executors.JavaExecutor");
            executorBuilder.addArgument(mainClass);
        }

        for (String argument : arguments.split(" ")) {
            if (argument.trim().isEmpty())
                continue;
            executorBuilder.addArgument(argument);
        }

        ProgramOutput output = executorBuilder.build().execute();
        return parseOutput(output.getStandardOutput(), isJunit);
    } finally {
        try {
            if (codeDirectory != null) {
                Files.walkFileTree(codeDirectory, new FileVisitor<Path>() {
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        return FileVisitResult.CONTINUE;
                    }

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

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

                    @Override
                    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                        Files.delete(dir);
                        return FileVisitResult.CONTINUE;
                    }
                });
            }
        } catch (IOException e) {
            ErrorWriter.getInstance().writeExceptionToExceptionAnalyzer(e, "Can't delete code directory");
        }
    }
}

From source file:com.excelsiorjet.api.util.Utils.java

public static void copyDirectory(Path source, Path target) throws IOException {
    Files.walkFileTree(source, new FileVisitor<Path>() {

        @Override/*from  ww  w  .j  a v  a2  s .c  om*/
        public FileVisitResult preVisitDirectory(Path subfolder, BasicFileAttributes attrs) throws IOException {
            Files.createDirectories(target.resolve(source.relativize(subfolder)));
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path sourceFile, BasicFileAttributes attrs) throws IOException {
            Path targetFile = target.resolve(source.relativize(sourceFile));
            copyFile(sourceFile, targetFile);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path sourceFile, IOException e) throws IOException {
            throw new IOException(Txt.s("Utils.CannotCopyFile.Error", sourceFile.toString(), e.getMessage()),
                    e);
        }

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

From source file:de.ks.file.FileStoreTest.java

@Before
public void setUp() throws Exception {
    controller.startOrResume(new ActivityHint(AddThoughtActivity.class));

    cleanup.cleanup();//from   ww  w.  j av a2 s.  c  o m
    fileStoreDir = TMPDIR + File.separator + "idnadrevTestStore";
    Options.store(fileStoreDir, FileOptions.class).getFileStoreDir();
    File file = new File(fileStoreDir);
    if (file.exists()) {
        Files.walkFileTree(file.toPath(), 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;
            }
        });
    }
}