批量删除文件-walkFileTree
private void handleFileTree(){
Files.walkFileTree(Paths.get("xxx"),new SimpleFileVisitor<Path>(){
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
return super.preVisitDirectory(dir, attrs);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return super.visitFile(file, attrs);
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
Files.delete(dir);
return super.postVisitDirectory(dir, exc);
}
});
}
批量拷贝文件-walk
private void copyFiles(){
String source = "d:\\123"
String target = "d:\\456"
Files.walk(Paths.get(source)).forEach(path -> {
// 更换路径
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))
}
})
}
文件写入写出
private static voidtransferTo(){
try(
FileChannel from =new FileInputStream("1.txt").getChannel();
FileChannel to =new FileOutputStream("2.txt").getChannel();
){
from.transferTo(0,from.size(),to);
}catch(Exception e){
e.printStackTrace();
}
}
文件操作
Path path = Paths.get("D:\\down");
System.out.println(Files.exists(path));
Files.createDirectory(path);
Files.createDirectories(path);
Files.copy(source,target);
Files.copy(source,target, StandardCopyOption.REPLACE_EXISTING);
Files.move(source,target, StandardCopyOption.ATOMIC_MOVE);
Files.delete(target);