package com.itcast;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/*
* 剪切一个非空文件夹
*/
public class Prac1 {
public static void main(String[] args) throws IOException {
File srcFile = new File("F:\\aa");
File destFile = new File("E:\\aa");
pasteFile(srcFile,destFile);
}
private static void pasteFile(File srcFile, File destFile) throws IOException {
// TODO Auto-generated method stub
File[] files = srcFile.listFiles();
for (File file : files) {
if (file.isFile()) {
copyFile(file,destFile);
deleteFile(file);
}else{
//递归,遍历文件夹
pasteFile(new File(srcFile,file.getName()), new File(destFile,file.getName()));
}
srcFile.delete();
}
}
private static void deleteFile(File srcFile) {
// TODO Auto-generated method stub
srcFile.delete();
}
//复制文件
private static void copyFile(File srcFile, File destFile) throws IOException{
//判断文件夹是否存在
if (!destFile.exists()) {
new File(destFile.getAbsolutePath()).mkdir();
}
//使用字节流读取文件
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(srcFile));
File newFile = new File(destFile,srcFile.getName());
//写入文件
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(newFile));
//定义一个缓冲数组
byte[] buf = new byte[1024];
int len = 0;
while ((len = bufferedInputStream.read(buf))!=-1) {
bufferedOutputStream.write(buf, 0, len);
}
//关闭资源。
bufferedOutputStream.close();
bufferedInputStream.close();
}
}
代码的所有IO异常都抛出去了,不是很好哈~