集册 Java实例教程 使用SimpleFileVisitor类复制目录

使用SimpleFileVisitor类复制目录

欢马劈雪     最近更新时间:2020-01-02 10:19:05

675
使用SimpleFileVisitor类复制目录

import java.io.IOException;

import java.nio.file.FileAlreadyExistsException;// from N o w J a v a . c o m - 时代Java

import java.nio.file.FileVisitOption;

import java.nio.file.FileVisitResult;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.SimpleFileVisitor;

import java.nio.file.attribute.BasicFileAttributes;

import java.util.EnumSet;


public class Main {

  public static void main(String[] args) {

    try {

      Path source = Paths.get("/home");

      Path target = Paths.get("/backup");

      Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS),

          Integer.MAX_VALUE, new CopyDirectory(source, target));

    } catch (IOException ex) {

      ex.printStackTrace();
      /* from 
      时 代 J a v a - nowjava.com*/

    }

  }


}


class CopyDirectory extends SimpleFileVisitor<Path> {

  private Path source;

  private Path target;


  public CopyDirectory(Path source, Path target) {

    this.source = source;

    this.target = target;

  }


  @Override

  public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)

      throws IOException {

    System.out.println("Copying " + source.relativize(file));

    Files.copy(file, target.resolve(source.relativize(file)));

    return FileVisitResult.CONTINUE;


  }


  @Override

  public FileVisitResult preVisitDirectory(Path directory,

      BasicFileAttributes attributes) throws IOException {

    Path targetDirectory = target.resolve(source.relativize(directory));

    
展开阅读全文