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.roda.core.storage.fs.FSUtils.java

/**
 * Copies a directory/file from one path to another
 * /*  w ww.ja v a 2  s .com*/
 * @param sourcePath
 *          source path
 * @param targetPath
 *          target path
 * @param replaceExisting
 *          true if the target directory/file should be replaced if it already
 *          exists; false otherwise
 * @throws AlreadyExistsException
 * @throws GenericException
 */
public static void copy(final Path sourcePath, final Path targetPath, boolean replaceExisting)
        throws AlreadyExistsException, GenericException {

    // check if we can replace existing
    if (!replaceExisting && FSUtils.exists(targetPath)) {
        throw new AlreadyExistsException("Cannot copy because target path already exists: " + targetPath);
    }

    // ensure parent directory exists or can be created
    try {
        if (targetPath != null) {
            Files.createDirectories(targetPath.getParent());
        }
    } catch (IOException e) {
        throw new GenericException("Error while creating target directory parent folder", e);
    }

    if (FSUtils.isDirectory(sourcePath)) {
        try {
            Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs)
                        throws IOException {
                    Files.createDirectories(targetPath.resolve(sourcePath.relativize(dir)));
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs)
                        throws IOException {
                    Files.copy(file, targetPath.resolve(sourcePath.relativize(file)));
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            throw new GenericException("Error while copying one directory into another", e);
        }
    } else {
        try {

            CopyOption[] copyOptions = replaceExisting
                    ? new CopyOption[] { StandardCopyOption.REPLACE_EXISTING }
                    : new CopyOption[] {};
            Files.copy(sourcePath, targetPath, copyOptions);
        } catch (IOException e) {
            throw new GenericException("Error while copying one file into another", e);
        }

    }

}

From source file:io.anserini.index.IndexWebCollection.java

static Deque<Path> discoverWarcFiles(Path p, final String suffix) {

    final Deque<Path> stack = new ArrayDeque<>();

    FileVisitor<Path> fv = new SimpleFileVisitor<Path>() {

        @Override// w  w  w .  j a  v  a2s  .  c  o m
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

            Path name = file.getFileName();
            if (name != null && name.toString().endsWith(suffix))
                stack.add(file);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
            if ("OtherData".equals(dir.getFileName().toString())) {
                LOG.info("Skipping: " + dir);
                return FileVisitResult.SKIP_SUBTREE;
            }
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFileFailed(Path file, IOException ioe) {
            LOG.error("Visiting failed for " + file.toString(), ioe);
            return FileVisitResult.SKIP_SUBTREE;
        }
    };

    try {
        Files.walkFileTree(p, fv);
    } catch (IOException e) {
        LOG.error("IOException during file visiting", e);
    }
    return stack;
}

From source file:org.springframework.cloud.config.monitor.FileMonitorConfiguration.java

private Set<File> walkDirectory(Path directory) {
    final Set<File> walkedFiles = new LinkedHashSet<File>();
    try {//from  w ww .j  ava 2 s . co m
        registerWatch(directory);
        Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                FileVisitResult fileVisitResult = super.preVisitDirectory(dir, attrs);
                // No need to monitor the git metadata
                if (dir.toFile().getPath().contains(".git")) {
                    return FileVisitResult.SKIP_SUBTREE;
                }
                registerWatch(dir);
                return fileVisitResult;
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                FileVisitResult fileVisitResult = super.visitFile(file, attrs);
                walkedFiles.add(file.toFile());
                return fileVisitResult;
            }

        });
    } catch (IOException e) {
        log.error("Failed to walk directory: " + directory.toString(), e);
    }
    return walkedFiles;
}

From source file:de.teamgrit.grit.checking.compile.GccCompileChecker.java

/**
 * This Method generates the command required to start the compiler. It
 * generates a list of strings that can be passed to a process builder.
 * /*from w  w w  .j  av  a 2s  . c o m*/
 * @param pathToProgramFile
 *            Where to look for the main file that will be compiled.
 * @param compilerName
 *            Which compiler to call
 * @param compilerFlags
 *            User supplied flags to be passed
 * @throws BadCompilerSpecifiedException
 *             When no compiler is given.
 * @throws FileNotFoundException
 *             When the file to be compiled does not exist
 * @return List of string with the command for the process builder.
 */
private List<String> createCompilerInvocation(Path pathToProgramFile, String compilerName,
        List<String> compilerFlags) throws BadCompilerSpecifiedException, FileNotFoundException {

    List<String> compilerInvocation = new LinkedList<>();
    // We need a compiler name. Without it we cannot compile anything and
    // abort.
    if (("".equals(compilerName)) || (compilerName == null)) {
        throw new BadCompilerSpecifiedException("No compiler specified.");
    } else {
        // search for a makefile
        Path programDirectory = null;
        if (!Files.isDirectory(pathToProgramFile)) {
            programDirectory = pathToProgramFile.getParent();
        } else {
            programDirectory = pathToProgramFile;
        }
        Collection<File> fileList = FileUtils.listFiles(programDirectory.toFile(),
                FileFilterUtils.fileFileFilter(), null);

        boolean hasMakefile = false;
        for (File f : fileList) {
            if (f.getName().matches("[Mm][Aa][Kk][Ee][Ff][Ii][Ll][Ee]")) {
                hasMakefile = true;
            }
        }

        if (hasMakefile) {
            // add the necessary flags for make and return the invocation -
            // we don't need more flags or parameters
            LOGGER.info("Found make-file. Compiling c-code with make.");
            compilerInvocation.add("make");
            compilerInvocation.add("-k");
            compilerInvocation.add("-s");
            return compilerInvocation;
        } else {
            compilerInvocation.add(compilerName);
            LOGGER.info("Compiling c-code with " + compilerName);
        }
    }

    // If compiler flags are passed, append them after the compiler name.
    // If we didn't get any we append nothing.
    if ((compilerFlags != null) && !(compilerFlags.isEmpty())) {
        if (!compilerFlags.contains("-c")) {
            compilerFlags.add("-c");
        }
        compilerInvocation.addAll(compilerFlags);
    }

    // Check for the existance of the program file we are trying to
    // compile.
    if ((pathToProgramFile == null) || (pathToProgramFile.compareTo(Paths.get("")) == 0)) {
        throw new FileNotFoundException("No file to compile specified");
    } else {

        if (Files.isDirectory(pathToProgramFile, LinkOption.NOFOLLOW_LINKS)) {
            // we have to be able to compile several .c files at the same
            // time so we need to find them
            RegexDirectoryWalker dirWalker = new RegexDirectoryWalker(".+\\.[Cc][Pp]?[Pp]?");
            try {
                Files.walkFileTree(pathToProgramFile, dirWalker);
            } catch (IOException e) {
                LOGGER.severe("Could not walk submission " + pathToProgramFile.toString()
                        + " while building compiler invocation: " + e.getMessage());
            }
            for (Path matchedFile : dirWalker.getFoundFiles()) {
                compilerInvocation
                        .add(matchedFile.toString().substring(pathToProgramFile.toString().length() + 1));
            }
        } else {
            throw new FileNotFoundException("Program file that should be compiled does not exist."
                    + "Filename : \"" + pathToProgramFile.toString() + "\"");
        }
    }
    return compilerInvocation;
}

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

public static boolean emptyDir(File file) {
    Path directory = file.toPath();
    if (!Files.isDirectory(directory)) {
        return true;
    }//  ww w.  j  av  a  2s  .com
    try {
        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 (exc == null) {
                    Files.delete(dir);
                    return FileVisitResult.CONTINUE;
                }
                return FileVisitResult.TERMINATE;
            }
        });
    } catch (IOException e) {
        IOUtils.log.error(format("error while trying to empty the directory %s", directory.toString()), e);
        return false;
    }
    return true;
}

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

@Override
public void recalculateChecksums() throws OwncloudResourceException {
    ResourceServiceProperties resourceProperties = properties.getResourceService();
    try {/*from  w w w.ja v  a2  s . c om*/
        Files.walkFileTree(resourceProperties.getLocation(), getFileVisitor());
    } catch (IOException e) {
        val logMessage = String.format(
                "Cannot recalculate the Checksum of all Files and Directories of Directory %s",
                resourceProperties.getLocation());
        log.error(logMessage, e);
        throw new OwncloudLocalResourceChecksumServiceException(logMessage, e);
    }
}

From source file:org.deventropy.shared.utils.DirectoryArchiverUtil.java

private static void createArchiveOfDirectory(final String archiveFile, final File srcDirectory,
        final String rootPathPrefix, final String archiveStreamFactoryConstant, final String encoding,
        final ArchiverCreateProcessor archiverCreateProcessorIn) throws IOException {

    /*/*  w  ww . j a v  a2  s.c  om*/
     * NOTE ON CHARSET ENCODING: Traditionally the ZIP archive format uses CodePage 437 as encoding for file name,
     * which is not sufficient for many international character sets.
     * Over time different archivers have chosen different ways to work around the limitation - the java.util.zip
     * packages simply uses UTF-8 as its encoding for example.
     * Ant has been offering the encoding attribute of the zip and unzip task as a way to explicitly specify the
     * encoding to use (or expect) since Ant 1.4. It defaults to the platform's default encoding for zip and UTF-8
     * for jar and other jar-like tasks (war, ear, ...) as well as the unzip family of tasks.
     */
    final ArchiverCreateProcessor archiveCreateProcessor = (null != archiverCreateProcessorIn)
            ? archiverCreateProcessorIn
            : new ArchiverCreateProcessor();
    ArchiveOutputStream aos = null;
    try {

        final ArchiveStreamFactory archiveStreamFactory = new ArchiveStreamFactory(encoding);
        final FileOutputStream archiveFileOutputStream = new FileOutputStream(archiveFile);
        final OutputStream decoratedArchiveFileOutputStream = archiveCreateProcessor
                .decorateFileOutputStream(archiveFileOutputStream);
        aos = archiveStreamFactory.createArchiveOutputStream(archiveStreamFactoryConstant,
                decoratedArchiveFileOutputStream);
        archiveCreateProcessor.processArchiverPostCreate(aos, encoding);

        final String normalizedRootPathPrefix = (null == rootPathPrefix || rootPathPrefix.isEmpty()) ? ""
                : normalizeName(rootPathPrefix, true);
        if (!normalizedRootPathPrefix.isEmpty()) {
            final ArchiveEntry archiveEntry = aos.createArchiveEntry(srcDirectory, normalizedRootPathPrefix);
            aos.putArchiveEntry(archiveEntry);
            aos.closeArchiveEntry();
        }

        final Path srcRootPath = Paths.get(srcDirectory.toURI());
        final ArchiverFileVisitor visitor = new ArchiverFileVisitor(srcRootPath, normalizedRootPathPrefix, aos);
        Files.walkFileTree(srcRootPath, visitor);

        aos.flush();
    } catch (ArchiveException e) {
        throw new IOException("Error creating archive", e);
    } finally {
        if (null != aos) {
            aos.close();
        }
    }
}

From source file:com.aol.advertising.qiao.injector.file.watcher.QiaoFileManager.java

/**
 * Find a file matching with the defined pattern from the source directory.
 *
 * @return/*from w ww.  ja  va  2s.c  o  m*/
 * @throws IOException
 */
private Path getNextFile() throws IOException {
    if (matchedFileSet.size() == 0) {
        CommonUtils.sleepQuietly(fileCheckDelayMillis);

        finder.reset();
        Files.walkFileTree(srcDirPath, finder);
        List<Path> files = finder.getMatchedFiles();
        for (Path f : files) {
            if (logger.isDebugEnabled())
                logger.debug("found " + f.toString());
            matchedFileSet.add(f);
        }
    }

    if (matchedFileSet.size() > 0) {
        Path ans = null;
        Iterator<Path> it = matchedFileSet.iterator();
        if (it.hasNext()) {
            ans = it.next();
            it.remove();
        }

        return ans;
    }

    return null;
}

From source file:org.pentaho.di.core.plugins.PluginFolderTest.java

private void cleanTempDir(Path path) throws IOException {
    Files.walkFileTree(path, new FileVisitor<Path>() {
        @Override/* www  .  j  a v a  2s .c  o m*/
        public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
            Files.delete(dir);
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
            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.CONTINUE;
        }
    });
}

From source file:org.apache.beam.runners.apex.ApexYarnLauncher.java

/**
 * Create a jar file from the given directory.
 * @param dir source directory/*from  w w  w.  ja v a 2  s.c  o m*/
 * @param jarFile jar file name
 * @throws IOException when file cannot be created
 */
public static void createJar(File dir, File jarFile) throws IOException {

    final Map<String, ?> env = Collections.singletonMap("create", "true");
    if (jarFile.exists() && !jarFile.delete()) {
        throw new RuntimeException("Failed to remove " + jarFile);
    }
    URI uri = URI.create("jar:" + jarFile.toURI());
    try (final FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {

        File manifestFile = new File(dir, JarFile.MANIFEST_NAME);
        Files.createDirectory(zipfs.getPath("META-INF"));
        try (final OutputStream out = Files.newOutputStream(zipfs.getPath(JarFile.MANIFEST_NAME))) {
            if (!manifestFile.exists()) {
                new Manifest().write(out);
            } else {
                FileUtils.copyFile(manifestFile, out);
            }
        }

        final java.nio.file.Path root = dir.toPath();
        Files.walkFileTree(root, new java.nio.file.SimpleFileVisitor<Path>() {
            String relativePath;

            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                relativePath = root.relativize(dir).toString();
                if (!relativePath.isEmpty()) {
                    if (!relativePath.endsWith("/")) {
                        relativePath += "/";
                    }
                    if (!relativePath.equals("META-INF/")) {
                        final Path dstDir = zipfs.getPath(relativePath);
                        Files.createDirectory(dstDir);
                    }
                }
                return super.preVisitDirectory(dir, attrs);
            }

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String name = relativePath + file.getFileName();
                if (!JarFile.MANIFEST_NAME.equals(name)) {
                    try (final OutputStream out = Files.newOutputStream(zipfs.getPath(name))) {
                        FileUtils.copyFile(file.toFile(), out);
                    }
                }
                return super.visitFile(file, attrs);
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                relativePath = root.relativize(dir.getParent()).toString();
                if (!relativePath.isEmpty() && !relativePath.endsWith("/")) {
                    relativePath += "/";
                }
                return super.postVisitDirectory(dir, exc);
            }
        });
    }
}