Java_文件夹拷贝

时间:2023-03-08 22:40:35

一.思路 

  * 文件夹的拷贝
  1.递归查找子孙级文件
  2.文件复制
  文件夹创建

二.代码  

  
package com.ahd.File;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; /***
* 文件夹的拷贝
1.递归查找子孙级文件
2.文件复制
文件夹创建 * @author Administrator
*
*/
public class CopyDirDemo {
public static void main(String[] args) {
//源文件夹
File src = new File("D:\\web13\\src");
//目标文件夹
File dest = new File("D:\\"); try {
copyDir(src,dest);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/***
*
* @param src
* @param dest
* @throws IOException
*/
public static void copyDir(File src, File dest) throws IOException {
// TODO Auto-generated method stub
//判断源文件夹是否是一个文件夹
if(src.isDirectory()){
dest=new File(dest,src.getName());
//在目标文件夹中创建文件夹
dest.mkdirs();
//获取原文件架中所有文件,文件并拷贝,文件夹创建
for(File f:src.listFiles()){
copyDir(f,new File(dest,f.getName()));
}
}else if(src.isFile()){
copyFile(src,dest);
} }
/***
* 拷贝文件
* @param src
* @param dest
* @throws IOException
*/
public static void copyFile(File src,File dest) throws IOException{
if(dest.isDirectory()){
try {
throw new Exception("目标是文件夹,不能拷贝");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(src.isFile()){
//创建流
InputStream is=new FileInputStream(src);
OutputStream os=new FileOutputStream(dest);
//拷贝
//一次拷贝字节数
byte []b=new byte[1024];
//记录字节数
int len=0;
while(-1!=(len=is.read(b))){
os.write(b,0,len);
}
//关闭流
os.close();
is.close();
}else{
System.out.println("错误,不是文件");
} }
}

copy