一、IO流方法
1)拷贝文件、文件夹
2)删除文件、文件夹
二、代码实现
// 从任意已知目录拷贝所有文件到另一目录1)拷贝文件、文件夹
public static void copyAll(File srcFile, File destFile) throws Exception {
if (srcFile.exists()) {
if (!destFile.exists()) {
destFile.mkdirs();
}
File[] file = srcFile.listFiles();
InputStream is = null;
OutputStream os = null;
for (File f : file) {
if (f.isFile()) {
is = new FileInputStream(f);
os = new FileOutputStream(new File(destFile, f.getName()));
int len = 0;
byte[] byt = new byte[1024];
while (-1 != (len = is.read(byt))) {
os.write(byt, 0, len);
}
try {
os.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
copyAll(f, new File(destFile, f.getName()));
}
}
} else {
System.out.println("源文件不存在");
}
}
2)删除文件、文件夹
//删除指定文件下的文件夹和文件
public static void delFile(File file){
if(file.exists()){
File[] flist=file.listFiles();
for(File f:flist){
if(f.isFile()){
f.delete();
}else{
delFile(f);
}
}
//当文件夹中文件全部删除后,再删除空文件夹
file.delete();
}else{
System.out.println("原文件不存在");
}
}
三、注意
1)代码可以使用,但是自己注意在main中调用下。