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, Set<FileVisitOption> options, int maxDepth,
        FileVisitor<? super Path> visitor) throws IOException 

Source Link

Document

Walks a file tree.

Usage

From source file:com.google.devtools.build.android.PackedResourceTarExpander.java

private void copyRemainingResources(final Path resourcePath, final Path packedResources) throws IOException {
    Files.walkFileTree(resourcePath, ImmutableSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
            new ConditionallyLinkingVisitor(packedResources, out, workingDirectory));
}

From source file:com.github.blindpirate.gogradle.util.IOUtils.java

public static void walkFileTreeSafely(Path path, FileVisitor<? super Path> visitor) {
    try {//from  w  ww .  j  av  a  2s .c  o  m
        Files.walkFileTree(path, EnumSet.noneOf(FileVisitOption.class), MAX_DFS_DEPTH, visitor);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:com.eqbridges.vertx.VerticleModuleMojo.java

private void copyFiles(File fromDir, File verticleFolder) throws MojoExecutionException {
    Path from = Paths.get(fromDir.toURI());
    Path to = Paths.get(verticleFolder.toURI());
    try {//from   ww  w.jav  a  2  s .  c  o  m
        Files.walkFileTree(from, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                new CopyDirVisitor(from, to, getLog()));
    } catch (IOException e) {
        throw new MojoExecutionException("unable to copy classes to verticleFolder", e);
    }
}

From source file:org.craftercms.studio.impl.v1.repository.disk.DiskContentRepository.java

/**
 * get immediate children for path/*from w w  w  .  j  a v  a  2 s .c o m*/
 * @param path path to content
 */
public RepositoryItem[] getContentChildren(String path) {
    final List<RepositoryItem> retItems = new ArrayList<RepositoryItem>();

    try {
        EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
        final String finalPath = path;
        Files.walkFileTree(constructRepoPath(finalPath), opts, 1, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path visitPath, BasicFileAttributes attrs) throws IOException {

                if (!visitPath.equals(constructRepoPath(finalPath))) {
                    RepositoryItem item = new RepositoryItem();
                    item.name = visitPath.toFile().getName();

                    String visitFolderPath = visitPath.toString();//.replace("/index.xml", "");
                    //Path visitFolder = constructRepoPath(visitFolderPath);
                    item.isFolder = visitPath.toFile().isDirectory();
                    int lastIdx = visitFolderPath.lastIndexOf(File.separator + item.name);
                    if (lastIdx > 0) {
                        item.path = visitFolderPath.substring(0, lastIdx);
                    }
                    //item.path = visitFolderPath.replace("/" + item.name, "");
                    item.path = item.path.replace(getRootPath().replace("/", File.separator), "");
                    item.path = item.path.replace(File.separator + ".xml", "");
                    item.path = item.path.replace(File.separator, "/");

                    if (!".DS_Store".equals(item.name)) {
                        logger.debug("ITEM NAME: {0}", item.name);
                        logger.debug("ITEM PATH: {0}", item.path);
                        logger.debug("ITEM FOLDER: ({0}): {1}", visitFolderPath, item.isFolder);
                        retItems.add(item);
                    }
                }

                return FileVisitResult.CONTINUE;
            }
        });
    } catch (Exception err) {
        // log this error
    }

    RepositoryItem[] items = new RepositoryItem[retItems.size()];
    items = retItems.toArray(items);
    return items;
}

From source file:net.sourceforge.pmd.cache.AbstractAnalysisCache.java

private URL[] getClassPathEntries() {
    final String classpath = System.getProperty("java.class.path");
    final String[] classpathEntries = classpath.split(File.pathSeparator);
    final List<URL> entries = new ArrayList<>();

    final SimpleFileVisitor<Path> fileVisitor = new SimpleFileVisitor<Path>() {
        @Override//from   w ww .  ja  v a2  s . com
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
            if (!attrs.isSymbolicLink()) { // Broken link that can't be followed
                entries.add(file.toUri().toURL());
            }
            return FileVisitResult.CONTINUE;
        }
    };
    final SimpleFileVisitor<Path> jarFileVisitor = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
            String extension = FilenameUtils.getExtension(file.toString());
            if ("jar".equalsIgnoreCase(extension)) {
                fileVisitor.visitFile(file, attrs);
            }
            return FileVisitResult.CONTINUE;
        }
    };

    try {
        for (final String entry : classpathEntries) {
            final File f = new File(entry);
            if (isClassPathWildcard(entry)) {
                Files.walkFileTree(new File(entry.substring(0, entry.length() - 1)).toPath(),
                        EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, jarFileVisitor);
            } else if (f.isFile()) {
                entries.add(f.toURI().toURL());
            } else {
                Files.walkFileTree(f.toPath(), EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                        fileVisitor);
            }
        }
    } catch (final IOException e) {
        LOG.log(Level.SEVERE, "Incremental analysis can't check execution classpath contents", e);
        throw new RuntimeException(e);
    }

    return entries.toArray(new URL[0]);
}

From source file:de.interactive_instruments.etf.testrunner.basex.BasexDbPartitioner.java

/**
 * Calculate single db chunk size./*from  w  ww.j  a v  a2  s . c  om*/
 *
 * @return long chunk size
 *
 * @throws IOException I/O error in visitor method
 */
private long getMaxChunkSize() throws IOException {
    // Calculate db chunk size
    DirSizeVisitor dbSizeVisitor = new DirSizeVisitor(filter);
    Files.walkFileTree(dbDir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), MAX_DIR_DEPTH, dbSizeVisitor);
    final long chunkSize = dbSizeVisitor.getSize() / maxDbSizeSizePerChunk
            + (dbSizeVisitor.getSize() % maxDbSizeSizePerChunk == 0 ? 0 : 1);
    return dbSizeVisitor.getSize() / chunkSize + 1;
}

From source file:se.trixon.filebydate.Operation.java

private boolean generateFileList() {
    mListener.onOperationLog("");
    mListener.onOperationLog(Dict.GENERATING_FILELIST.toString());
    PathMatcher pathMatcher = mProfile.getPathMatcher();

    EnumSet<FileVisitOption> fileVisitOptions = EnumSet.noneOf(FileVisitOption.class);
    if (mProfile.isFollowLinks()) {
        fileVisitOptions = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
    }/*from  ww w.  ja v a2  s.  c o m*/

    File file = mProfile.getSourceDir();
    if (file.isDirectory()) {
        FileVisitor fileVisitor = new FileVisitor(pathMatcher, mFiles, this);
        try {
            if (mProfile.isRecursive()) {
                Files.walkFileTree(file.toPath(), fileVisitOptions, Integer.MAX_VALUE, fileVisitor);
            } else {
                Files.walkFileTree(file.toPath(), fileVisitOptions, 1, fileVisitor);
            }

            if (fileVisitor.isInterrupted()) {
                return false;
            }
        } catch (IOException ex) {
            Xlog.e(getClass(), ex.getLocalizedMessage());
        }
    } else if (file.isFile() && pathMatcher.matches(file.toPath().getFileName())) {
        mFiles.add(file);
    }

    if (mFiles.isEmpty()) {
        mListener.onOperationLog(Dict.FILELIST_EMPTY.toString());
    } else {
        Collections.sort(mFiles);
    }

    return true;
}

From source file:de.interactive_instruments.etf.testrunner.basex.BasexDbPartitioner.java

/**
 * Creates all databases.//from  ww w  .j av a 2 s.c  om
 *
 * @throws IOException          I/O error in visitor method
 * @throws InterruptedException thread is interrupted
 */
public void createDatabases() throws IOException, InterruptedException {
    final long maxChunkSize = getMaxChunkSize();
    // Create databases
    FileVisitor<Path> basexPartitioner = new BasexFileVisitorPartitioner(maxChunkSize);
    Files.walkFileTree(dbDir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), MAX_DIR_DEPTH, basexPartitioner);
    if (Thread.currentThread().isInterrupted()) {
        throw new InterruptedException();
    }
    logger.info("Added " + fileCount + " files (" + FileUtils.byteCountToDisplaySize(size) + ") to "
            + getDbCount() + " database(s) ");
    logger.info("Optimizing database " + dbBaseName + "-0");
    flushAndOptimize(ctx);
    new Open(dbBaseName + "-0").execute(ctx);
    new Close().execute(ctx);
    ctx.close();
    logger.info("Import completed");

}

From source file:org.craftercms.studio.impl.v1.repository.disk.DiskContentRepository.java

/**
 * get the version history for an item//from w  w  w . j  ava2 s .  com
 * @param path - the path of the item
 */
public VersionTO[] getContentVersionHistory(String path) {
    final List<VersionTO> versionList = new ArrayList<VersionTO>();

    try {
        final String pathToContent = path.substring(0, path.lastIndexOf(File.separator));
        final String filename = path.substring(path.lastIndexOf(File.separator) + 1);

        Path versionPath = constructVersionRepoPath(pathToContent);

        EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);

        Files.walkFileTree(versionPath, opts, 1, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path visitPath, BasicFileAttributes attrs) throws IOException {
                String versionFilename = visitPath.toString();

                if (versionFilename.contains(filename)) {
                    VersionTO version = new VersionTO();
                    String label = versionFilename.substring(versionFilename.lastIndexOf("--") + 2);

                    BasicFileAttributes attr = Files.readAttributes(visitPath, BasicFileAttributes.class);

                    version.setVersionNumber(label);
                    version.setLastModifier("ADMIN");
                    version.setLastModifiedDate(new Date(attr.lastModifiedTime().toMillis()));
                    version.setComment("");

                    versionList.add(version);
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (Exception err) {
        logger.error("error while getting history for content item " + path);
        logger.debug("error while getting history for content item " + path, err);
    }
    final List<VersionTO> finalVersionList = new ArrayList<VersionTO>();
    if (versionList.size() > 0) {
        Collections.sort(versionList);
        VersionTO latest = versionList.get(versionList.size() - 1);
        String latestVersionLabel = latest.getVersionNumber();
        int temp = latestVersionLabel.indexOf(".");
        String currentMajorVersion = latestVersionLabel.substring(0, temp);

        for (int i = versionList.size(); i > 0; i--) {
            VersionTO v = versionList.get(i - 1);
            String versionId = v.getVersionNumber();
            boolean condition = !versionId.startsWith(currentMajorVersion) && !versionId.endsWith(".0");
            if (condition)
                continue;
            finalVersionList.add(v);
        }
    }
    //Collections.reverse(versionList);
    VersionTO[] versions = new VersionTO[finalVersionList.size()];
    versions = finalVersionList.toArray(versions);
    return versions;
}

From source file:de.interactive_instruments.etf.testrunner.basex.BasexDbPartitioner.java

/**
 * Perform a dry run to gather information about the number of files which will be imported
 * and the number of databases that will be created.
 * <p>/*  w ww. j  a  v a2  s  .  co  m*/
 * Important: call reset() after a dry run
 * </p>
 *
 * @throws IOException I/O error in visitor method
 */
public void dryRun() throws IOException {
    // Calculate db chunk size
    final long maxChunkSize = getMaxChunkSize();
    // Create databases
    FileVisitor<Path> basexPartitioner = new BasexFileVisitorDryRun(filter, maxChunkSize);
    Files.walkFileTree(dbDir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), MAX_DIR_DEPTH, basexPartitioner);
}