给你看一下代码
import java.io.*;
class SendFile
{
static String url1 = "d:\\nihao";
static String url2 = "e:\\ccpy";
public static void main(String[] args) throws IOException
{
//创建目标文件夹
(new File(url2)).mkdirs();
//获取源文件夹当前下的文件或目录
File[] file = (new File(url1)).listFiles();
for (int i =0;i<file.length ;i++ )
{
if (file[i].isFile()) {
// 复制文件
copyFile(file[i],new File(url2+file[i].getName()));
}
if (file[i].isDirectory())
{
//复制目录
String sourDir = url1+File.separator+file[i].getName();
String targDir = url2+File.separator+file[i].getName();
copyDirectiory(sourDir,targDir);
}
}
}
//复制文件
public static void copyFile(File sour,File targ)
{
FileInputStream fis = null;
FileOutputStream fos = null;
try
{
fis = new FileInputStream(sour);
fos = new FileOutputStream(targ);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream bos = new BufferedOutputStream(fos);
//缓冲数组
byte[] buf = new byte[1024*5];
int len = 0;
while ((len=bis.read(buf))!=-1)
{
bos.write(buf,0,len);
bos.flush();
}
bis.close();
bos.close();
fis.close();
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void copyDirectiory(String sourDir,String targDir)throws IOException
{
//新建文件目录
(new File(targDir)).mkdirs();
//获取源文件当前下的文件或目录
File[] file = (new File(sourDir)).listFiles();
for (int i = 0;i<file.length ;i++ )
{
if (file[i].isFile())
{
//源文件
File sourFile = file[i];
//目标文件
File targFile = new File(new File(targDir).getAbsolutePath()+File.separator+file[i].getName());
copyFile(sourFile,targFile);
}
if (file[i].isDirectory())
{
//准备复制的源文件夹
String dir1 = sourDir+"/"+file[i].getName();
//准备复制的目标文件夹
String dir2 = targDir+""+file[i].getName();
copyDirectiory(dir1,dir2);
}
}
}
}
|