Java java.nio.file.FileVisitOption 代码实例

・22 分钟阅读

以下是展示如何使用java.nio.file.FileVisitOption的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


public static OperationResult copyFileTree(Path source, Path target, Predicate<Path> filter) {
        OperationResult or = new OperationResult();
      try {
        if (Files.notExists(target)) 
                Files.createDirectories(target);
        Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                        throws IOException
                    {
                        Path targetdir = target.resolve(source.relativize(dir));
                        try {
                            Files.copy(dir, targetdir, StandardCopyOption.COPY_ATTRIBUTES);
                        } 
                        catch (FileAlreadyExistsException x) {
                             if (!Files.isDirectory(targetdir))
                                 throw x;
                        }
                        return FileVisitResult.CONTINUE;
                    }
                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                        throws IOException
                    {
                        if ((filter == null) || filter.test(file))
                                Files.copy(file, target.resolve(source.relativize(file)), StandardCopyOption.COPY_ATTRIBUTES);
                        return FileVisitResult.CONTINUE;
                    }
                });
} 
      catch (IOException x) {
        or.error("Error copying file tree: " + x);
}
      return or;
  }
 

实例 2


public void checkDir(Location dir) throws CommonException {
        try {
                Files.walkFileTree(dir.path, EnumSet.of(FileVisitOption.FOLLOW_LINKS), 1, this);
        } catch (IOException e) {
                throw new CommonException("Error walking file tree", e);
        }
}
 

实例 3


/**
 * Use walkFileTree methods instead
 */
@Deprecated
public LinkedList<File> fileWalk() {
        resultList.clear();
        for (File f : dirToSearch) {
                try {
                        if (noSub && folderOnly) {
                                Files.walkFileTree(f.toPath(), EnumSet.noneOf(FileVisitOption.class), 2, new FileVisitor());
                        } else if (noSub && !folderOnly) {
                                Files.walkFileTree(f.toPath(), EnumSet.noneOf(FileVisitOption.class), 1, new FileVisitor());
                        } else {
                                Files.walkFileTree(f.toPath(), new FileVisitor());
                        }
                } catch (IOException e) {
                        e.printStackTrace(); // should not reach this...
                }
        }
        dirToSearch.clear();
        return new LinkedList<File>(resultList);
}
 

实例 4


/**
 * Copies the unpacked nar libraries and files into the projects target area
 */
public final void narExecute()
    throws MojoExecutionException, MojoFailureException
{
    List narArtifacts = getNarManager().getNarDependencies( "compile" );
    List dependencies = getNarManager().getAttachedNarDependencies( narArtifacts, classifiers );
    // this may make some extra copies...
    for ( Iterator d = dependencies.iterator(); d.hasNext(); )
    {
        Artifact dependency = (Artifact) d.next();
        getLog().debug( "Assemble from " + dependency );
        // FIXME reported to maven developer list, isSnapshot
        // changes behaviour
        // of getBaseVersion, called in pathOf.
        dependency.isSnapshot();
        File srcDir =
            getLayout().getNarUnpackDirectory( getUnpackDirectory(), getNarManager().getNarFile( dependency ) );
        // File srcDir = new File( getLocalRepository().pathOf( dependency ) );
        // srcDir = new File( getLocalRepository().getBasedir(), srcDir.getParent() );
        // srcDir = new File( srcDir, "nar/" );
        File dstDir = getTargetDirectory();
        try
        {
            FileUtils.mkdir( dstDir.getPath() );
            getLog().debug( "SrcDir: " + srcDir );
            if ( srcDir.exists() )
            {
                EnumSet<FileVisitOption> opts = EnumSet.noneOf( FileVisitOption.class );
                NarUtil.TreeCopier tc = new NarUtil.TreeCopier( srcDir.toPath(), dstDir.toPath(), getLog() );
                Files.walkFileTree( srcDir.toPath(), opts, MAX_VALUE, tc );
            }
        }
        catch ( IOException ioe )
        {
            throw new MojoExecutionException( "Failed to copy directory for dependency " + dependency + " from "
                + srcDir + " to " + dstDir, ioe );
        }
    }
}
 

实例 5


private void uninstallLanguage (final String lang)
        throws Exception
{
    if (!tessdata.get()
            .exists()) {
        return;
    }
    // Clean up relevant files in the folder
    Files.walkFileTree(
            tessdata.get().toPath(),
            EnumSet.noneOf(FileVisitOption.class),
            1,
            new SimpleFileVisitor<Path>()
    {
        @Override
        public FileVisitResult visitFile (Path file,
                                          BasicFileAttributes attrs)
                throws IOException
        {
            Path name = file.getName(file.getNameCount() - 1);
            logger.debug("Visiting {}, name {}", file, name);
            if (name.toString()
                    .startsWith(lang + ".")) {
                logger.info("Removing file {}", file);
                try {
                    // Try immediate delete
                    Files.delete(file);
                } catch (AccessDeniedException ex) {
                    logger.info(
                            "Cannot delete {}, will post a delete command",
                            file);
                    // Post a delete command
                    appendCommand(
                            descriptor.getDeleteCommand(file));
                }
            }
            return FileVisitResult.CONTINUE;
        }
    });
}
 

实例 6


private BlockingAction<Void> copyInternal(String from, String to, boolean recursive, Handler<AsyncResult<Void>> handler) {
  Objects.requireNonNull(from);
  Objects.requireNonNull(to);
  return new BlockingAction<Void>(handler) {
    public Void perform() {
      try {
        Path source = vertx.resolveFile(from).toPath();
        Path target = vertx.resolveFile(to).toPath();
        if (recursive) {
          Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
              new SimpleFileVisitor<Path>() {
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                    throws IOException {
                  Path targetDir = target.resolve(source.relativize(dir));
                  try {
                    Files.copy(dir, targetDir);
                  } catch (FileAlreadyExistsException e) {
                    if (!Files.isDirectory(targetDir)) {
                      throw e;
                    }
                  }
                  return FileVisitResult.CONTINUE;
                }
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
                    throws IOException {
                  Files.copy(file, target.resolve(source.relativize(file)));
                  return FileVisitResult.CONTINUE;
                }
              });
        } else {
          Files.copy(source, target);
        }
      } catch (IOException e) {
        throw new FileSystemException(e);
      }
      return null;
    }
  };
}
 

实例 7


@Override
public SortedSet<Project.NameKey> list() {
  // The results of this method are cached by ProjectCacheImpl. Control only
  // enters here if the cache was flushed by the administrator to force
  // scanning the filesystem. Don't rely on the cached names collection.
  namesUpdateLock.lock();
  try {
    ProjectVisitor visitor = new ProjectVisitor();
    try {
      Files.walkFileTree(basePath, EnumSet.of(FileVisitOption.FOLLOW_LINKS),
          Integer.MAX_VALUE, visitor);
    } catch (IOException e) {
      log.error("Error walking repository tree " + basePath.toAbsolutePath(),
          e);
    }
    return Collections.unmodifiableSortedSet(visitor.found);
  } finally {
    namesUpdateLock.unlock();
  }
}
 

实例 8


@Override
JSONStreamAware processRequest(HttpServletRequest req) {
    JSONObject response = new JSONObject();
    if (!Files.isReadable(PLUGINS_HOME)) {
        return JSONResponses.fileNotFound(PLUGINS_HOME.toString());
    }
    PluginDirListing pluginDirListing = new PluginDirListing();
    try {
        Files.walkFileTree(PLUGINS_HOME, EnumSet.noneOf(FileVisitOption.class), 2, pluginDirListing);
    } catch (IOException e) {
        return JSONResponses.fileNotFound(e.getMessage());
    }
    JSONArray plugins = new JSONArray();
    pluginDirListing.getDirectories().forEach(dir -> plugins.add(Paths.get(dir.toString()).getFileName().toString()));
    response.put("plugins", plugins);
    return response;
}
 

实例 9


public void iterate() {
    final List<Path> files = new ArrayList<>();
    final PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern);
    final FileVisitor<Path> fileVisitor = new SimpleFileVisitor<Path>() {
        boolean firstDir = true;
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attribs) {
            if (matcher.matches(file.getFileName())) {
                files.add(file);
            }
            return FileVisitResult.CONTINUE;
        }
        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            if (recursive || firstDir) {
                firstDir = false;
                return FileVisitResult.CONTINUE;
            }
            return FileVisitResult.SKIP_SUBTREE;
        }
    };
    try {
        Files.walkFileTree(dir, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE, fileVisitor);
    } catch (IOException e) {
        LOG.error("Failed to read directory: " + e.getMessage());
    }
    // Sort files
    if (this.comparator != null) {
        Collections.sort(files, comparator);
    } else {
        Collections.sort(files);
    }
    // Iterate through all files
    for (Path file : files) {                
        handleFile(file);
    }
}
 

实例 10


public void fix(Path buildRoot) throws IOException
{
    // Find all of the *.mod files
    PathFinder finder = new PathFinder();
    finder.setFileMatcher("glob:**/*.mod");
    finder.setBase(buildRoot);
    // Matcher for target directories
    PathMatcher targetMatcher = PathMatchers.getMatcher("glob:**/target/**");
    PathMatcher testMatcher = PathMatchers.getMatcher("glob:**/test/**");
    System.out.printf("Walking path: %s%n",buildRoot);
    Set<FileVisitOption> options = Collections.emptySet();
    Files.walkFileTree(buildRoot,options,30,finder);
    System.out.printf("Found: %d hits%n",finder.getHits().size());
    int count = 0;
    for (Path path : finder.getHits())
    {
        if (Files.isDirectory(path))
        {
            // skip
            continue;
        }
        if (targetMatcher.matches(path))
        {
            // skip
            continue;
        }
        if (testMatcher.matches(path))
        {
            // skip
            continue;
        }
        if (processModFile(path))
        {
            count++;
        }
    }
    System.out.printf("Processed %,d modules",count);
}
 

实例 11


/**
 *
 * @return
 * @throws IOException
 */
MediaTreeVisitor visit() throws IOException {
    Set<FileVisitOption> options = new HashSet<>(1);
    if (followLinks) {
        options.add(FileVisitOption.FOLLOW_LINKS);
    }
    Files.walkFileTree(root, options, Integer.MAX_VALUE, this);
    return this;
}
 

实例 12


@Override
JSONStreamAware processRequest(HttpServletRequest req) {
    JSONObject response = new JSONObject();
    if (!Files.isReadable(PLUGINS_HOME)) {
        return JSONResponses.fileNotFound(PLUGINS_HOME.toString());
    }
    PluginDirListing pluginDirListing = new PluginDirListing();
    try {
        Files.walkFileTree(PLUGINS_HOME, EnumSet.noneOf(FileVisitOption.class), 2, pluginDirListing);
    } catch (IOException e) {
        return JSONResponses.fileNotFound(e.getMessage());
    }
    JSONArray plugins = new JSONArray();
    pluginDirListing.getDirectories().forEach(dir -> plugins.add(Paths.get(dir.toString()).getFileName().toString()));
    response.put("plugins", plugins);
    return response;
}
 

实例 13


public List<File> all() throws IOException {
        if (!Strings.isNullOrEmpty(requiredName) || !Strings.isNullOrEmpty(requiredExtension)) {
                return inclusive();
        }
        final int recursionDepth = recursive ? Integer.MAX_VALUE : 1;
        java.nio.file.Files.walkFileTree(Paths.get(dir.getAbsolutePath()), Collections.<FileVisitOption>emptySet(), recursionDepth, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                        final File file = path.toFile();
                        if (file.isFile()) {
                                result.add(file);
                        }
                        return FileVisitResult.CONTINUE;
                }
        });
        return ImmutableList.copyOf(result);
}
 

实例 14


public void copyDirContentsToDir(File fromDir, File toDir) throws IOException{
   createDir(fromDir);
   createDir(toDir);
   EnumSet<FileVisitOption> options = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
   Files.walkFileTree(
      fromDir.toPath(),
      options,
      Integer.MAX_VALUE,
      new DirectoryDuplicator(fromDir, toDir, this)
   );
}
 

实例 15


private void list(Path path, String packageName, final Set<Kind> kinds,
            boolean recurse, final ListBuffer<JavaFileObject> results)
            throws IOException {
        if (!Files.exists(path))
            return;
        final Path pathDir;
        if (isDirectory(path))
            pathDir = path;
        else {
            FileSystem fs = getFileSystem(path);
            if (fs == null)
                return;
            pathDir = fs.getRootDirectories().iterator().next();
        }
        String sep = path.getFileSystem().getSeparator();
        Path packageDir = packageName.isEmpty() ? pathDir
                : pathDir.resolve(packageName.replace(".", sep));
        if (!Files.exists(packageDir))
            return;
/* Alternate impl of list, superceded by use of Files.walkFileTree */
//        Deque<Path> queue = new LinkedList<Path>();
//        queue.add(packageDir);
//
//        Path dir;
//        while ((dir = queue.poll()) != null) {
//            DirectoryStream<Path> ds = dir.newDirectoryStream();
//            try {
//                for (Path p: ds) {
//                    String name = p.getFileName().toString();
//                    if (isDirectory(p)) {
//                        if (recurse && SourceVersion.isIdentifier(name)) {
//                            queue.add(p);
//                        }
//                    } else {
//                        if (kinds.contains(getKind(name))) {
//                            JavaFileObject fe =
//                                PathFileObject.createDirectoryPathFileObject(this, p, pathDir);
//                            results.append(fe);
//                        }
//                    }
//                }
//            } finally {
//                ds.close();
//            }
//        }
        int maxDepth = (recurse ? Integer.MAX_VALUE : 1);
        Set<FileVisitOption> opts = EnumSet.of(FOLLOW_LINKS);
        Files.walkFileTree(packageDir, opts, maxDepth,
                new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
                Path name = dir.getFileName();
                if (name == null || SourceVersion.isIdentifier(name.toString())) // JSR 292?
                    return FileVisitResult.CONTINUE;
                else
                    return FileVisitResult.SKIP_SUBTREE;
            }
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                if (attrs.isRegularFile() && kinds.contains(getKind(file.getFileName().toString()))) {
                    JavaFileObject fe =
                        PathFileObject.createDirectoryPathFileObject(
                            JavacPathFileManager.this, file, pathDir);
                    results.append(fe);
                }
                return FileVisitResult.CONTINUE;
            }
        });
    }
 
讨论
淘淘あ西西 profile image