Java文件夹复制及删除(递归实现)
文件复制
oldpath为原文件夹
newpath为新父路径(不包括文件夹名)
import java.io.*;
public class copyfile {
public static void main(String[] args) {
// 原文件夹路径
String oldPath = "C:\\Users\\dell\\桌面\\上课\\信息安全综合实验";
// 目标父路径
String newPath = "C:\\Users\\dell\\桌面";
File fileIn = new File(oldPath);
File fileOut = new File(newPath);
copy(fileIn, fileOut);
}
public static void copy(File fileIn, File fileOut){
File out = new File(fileOut.getAbsolutePath() + "\\" + fileIn.getName());
if (!out.exists()){
boolean b = out.mkdir();
}
File[] fileIns = fileIn.listFiles();
if (fileIns == null){
System.out.println("文件夹为空!");
}
else {
for (File in : fileIns) {
if (in.isFile()){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(in.getAbsolutePath());
fos = new FileOutputStream(out.getAbsolutePath() + "\\" + in.getName());
byte[] b = new byte[1024];
while (fis.read(b) != -1){
fos.write(b);
}
System.out.println(in.getName() + " ->文件夹: " + out.getName());
fos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
assert fis != null;
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
assert fos != null;
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
else if (in.isDirectory()){
System.out.println("源子文件夹" + in.getAbsolutePath());
System.out.println("目标子文件夹" + out.getAbsolutePath());
copy(in,out);
} else {
System.out.println("错误文件");
}
}
}
}
}
文件夹删除
import java.io.File;
public class deleteFile {
public static void main(String[] args) {
String dPath = "C:\\Users\\dell\\桌面\\信息安全综合实验";
File df = new File(dPath);
delete(df);
}
public static void delete(File df){
File[] files = df.listFiles();
assert files != null;
for (File file : files) {
if (file.isFile()){
boolean b = file.delete();
if(b){
System.out.println("删除文件 " + file.getAbsolutePath());
} else {
System.out.println(file.getAbsolutePath() + " 删除失败");
}
} else if (file.isDirectory()){
delete(file);
} else {
System.out.println("删除错误");
}
}
boolean b = df.delete();
if(b){
System.out.println("删除文件夹 " + df.getAbsolutePath());
} else {
System.out.println(df.getAbsolutePath() + " 删除失败");
}
}
}