习题:
import java.io.File;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
class CopyAllFiles
{
public static void main(String[] args)
{
//源目录
File srcFolder=new File("D:\\KwDownload");
//目的地目录
File destFloder=new File("E:\\music");
long startTime=System.currentTimeMillis();
//将源目录下的所有文件及文件夹复制到指定目录
boolean flag=copyAllFiles(srcFolder,destFloder);
long endTime=System.currentTimeMillis();
long resultTime=endTime-startTime;
if(flag)
{
System.out.println("复制成功!共用时"+resultTime+"毫秒("+(resultTime/1000)+"秒)");
}
}
/**
* 文件及文件夹复制工具
* @param src 源目录
* @param dest 目的地目录
* @return flag 返回true表示复制成功,否则复制失败
*/
public static boolean copyAllFiles(File src,File dest)
{
boolean flag=false;
if(!dest.exists())
{
dest.mkdir();
}
File[] fileArr=src.listFiles(); //将源目录下的对象封装进File数组
for(File f:fileArr) //遍历File中的对象
{
if(f.isDirectory()) //判断File对象是否是目录
{
File newFolder=new File(dest,f.getName());
newFolder.mkdir(); //创建目的地目录创建遍历到的文件夹
copyAllFiles(f,newFolder); //如果遍历到的是目录,递归循环操作
//System.out.println(f.getName()+"---"+newFolder.getName());
}
else
{
//调用字节流复制方法
//CopyBinaryFile(f.getAbsolutePath(),dest.getAbsolutePath().concat("\\").concat(f.getName()));
CopyBinaryFile(f.getAbsolutePath(),new File(dest,f.getName()).getAbsolutePath());
//System.out.println(f.getAbsolutePath());
//System.out.println(new File(dest,f.getName()).getAbsolutePath());
}
if(f!=null)
{
flag=true;
}
}
return flag;
}
/**
* 字节流文件复制工具
* @param src 数据源
* @param dest 目的地
* @return flag 如果为true,表示复制成功,否则,复制失败。
*/
public static boolean CopyBinaryFile(String src,String dest)
{
boolean flag=false;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try
{
bis=new BufferedInputStream(new FileInputStream(src));
bos=new BufferedOutputStream(new FileOutputStream(dest));
byte[] bys=new byte[1024];
int len=0;
while((len=bis.read(bys))!=-1)
{
//写入数据
bos.write(bys,0,len);
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally
{
if(bos!=null)
{
try
{
//释放资源
bos.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
if(bis!=null)
{
try
{
//释放资源
bis.close();
flag=true;
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
return flag;
}
}