jdk7 Files 快速进行多级文件遍历删除及拷贝
一: 多级文件遍历
import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; /** * jdk 7 Files 文件树遍历 */ @Slf4j public class TestFilesWalkFileTree { public static void main(String[] args) { try { Files.walkFileTree(Paths.get("D:\test\jdk8"),new SimpleFileVisitor<Path>(){ // 进入文件目录前 @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { log.error("进入目录---{}",dir); return super.preVisitDirectory(dir, attrs); } // 访问文件 如需删除,在此方法内删除文件 @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { log.error("文件---{}",file); // Files.delete(file); return super.visitFile(file, attrs); } // 访问失败操作 @Override public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { log.error("访问文件失败---{}",file); return super.visitFileFailed(file, exc); } // 退出文件目录操作 如需删除,在此方法内删除目录 @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { log.error("退出目录---{}",dir); // Files.delete(dir); return super.postVisitDirectory(dir, exc); } }); } catch (IOException e) { throw new RuntimeException(e); } } }
二:多级文件拷贝
import java.nio.file.Files; import java.nio.file.Paths; /** * jdk7 Files 多级文件拷贝 */ public class TestFIlesCopy { public static void main(String[] args) throws Exception { String source="D:\test\jdk8"; String target="D:\test\jdk8_back"; Files.walk(Paths.get(source)).forEach(path -> { try { String targetName=path.toString().replace(source,target); // 是目录创建目录 if(Files.isDirectory(path)){ Files.createDirectory(Paths.get(targetName)); }else if (Files.isRegularFile(path)){ // 进行文件拷贝 Files.copy(path,Paths.get(targetName)); } }catch (Exception e){ e.printStackTrace(); } }); } }