集册 Java实例教程 使用FileVisitor递归移动文件

使用FileVisitor递归移动文件

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

519
使用FileVisitor递归移动文件
/**
 from
* 时 代 J a v a - nowjava.com 
**/

import java.io.IOException;

import java.nio.file.FileVisitOption;

import java.nio.file.FileVisitResult;

import java.nio.file.FileVisitor;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.attribute.BasicFileAttributes;

import java.nio.file.attribute.FileTime;

import java.util.EnumSet;

import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;

import static java.nio.file.StandardCopyOption.COPY_ATTRIBUTES;

import static java.nio.file.StandardCopyOption.ATOMIC_MOVE;


class MoveTree implements FileVisitor<Object> {
/**
 from
* nowjava - 时  代  Java 
**/

  Path moveFrom;

  Path moveTo;

  static FileTime time = null;


  public MoveTree(Path moveFrom, Path moveTo) {

    this.moveFrom = moveFrom;

    this.moveTo = moveTo;

  }

  void moveSubTree(Path moveFrom, Path moveTo) throws IOException {

    try {

      Files.move(moveFrom, moveTo, REPLACE_EXISTING, ATOMIC_MOVE);

    } catch (IOException e) {

      System.err.println("Unable to move " + moveFrom + " [" + e + "]");

    }

  }


  @Override

  public FileVisitResult postVisitDirectory(Object dir, IOException exc)

      throws IOException {

    Path newdir = moveTo.resolve(moveFrom.relativize((Path) dir));

    try {

      Files.setLastModifiedTime(newdir, time);

      Files.delete((Path) dir);

    } catch (IOException e) {

      System.err.println("Unable to copy all attributes to: " + newdir + " ["

          + e + "]");

    }

    return FileVisitResult.CONTINUE;

  }


  @Override

  public FileVisitResult preVisitDirectory(Object dir, BasicFileAttributes attrs)

      throws IOException {

    System.out.println("Move directory: " + (Path) dir);

    Path newdir = moveTo.resolve(moveFrom.relativize((Path) dir));

    try {

      Files.copy((Path) dir, newdir, REPLACE_EXISTING, COPY_ATTRIBUTES);

      time = Files.getLastModifiedTime((Path) dir);

    } catch (IOException e) {

      System.err.println("Unable to move " + newdir + " [" + e + "]");

      return FileVisitResult.SKIP_SUBTREE;

    }


    return FileVisitResult.CONTINUE;

  }


  @Override

  public FileVisitResult visitFile(Object file, BasicFileAttributes attrs)

      throws IOException {

    System.out.println("Move file: " + (Path) file);

    moveSubTree((Path) file, moveTo.resolve(moveFrom.relativize((Path) file)));

    return FileVisitResult.CONTINUE;

  }


  @Override

  public FileVisitResult visitFileFailed(Object file, IOException exc)

      
展开阅读全文