正好上午做了这个练习,你参考看看复制代码
- 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 Test1 {
- /**
- * @param args
- * 复制文件夹
- * @throws IOException
- */
- public static void main(String[] args) throws IOException {
- File src = new File("C:\\Documents and Settings\\Administrator\\桌面\\2.22.02");
- File des = new File("D:\\360安全浏览器下载") ;
- copyDir(src, des);
- //copyFile(src, des);
- }
- //复制文件夹
- public static void copyDir(File src, File des) throws IOException{
- if(!des.exists()){ //目录不存在,则新建目录
- des.mkdir();
- }
- File[] files = src.listFiles();
- for(File file: files){
- String fileName = file.getName(); //文件名
- System.out.println(fileName);
- File desFile = new File(des.getAbsolutePath()+"\\"+fileName); //目标文件
- if(!file.isDirectory()){
- BufferedInputStream buis = new BufferedInputStream(new FileInputStream(file));
- BufferedOutputStream buos = new BufferedOutputStream(new FileOutputStream(desFile));
- byte[] bys = new byte[1024];
- int len = 0;
- while((len = buis.read(bys)) != -1){
- buos.write(bys, 0, len);
- }
- buis.close();
- buos.close();
- }else{
- desFile.mkdir();
- copyDir(file, desFile); //如果是文件夹,递归调用
- }
- }
- }
- //复制文件
- public static void copyFile(File src, File des) throws IOException{
- String fileName = src.getName(); //源文件名
- BufferedInputStream buis = new BufferedInputStream(new FileInputStream(src));
- String desPath = des.getAbsolutePath()+"\\"+fileName; //目标文件绝对路径
- File desFile = new File(desPath); //目标文件
- BufferedOutputStream buos = new BufferedOutputStream(new FileOutputStream(desFile));
- byte[] bys = new byte[1024];
- int len = 0;
- while((len = buis.read(bys)) != -1){
- buos.write(bys, 0, len);
- }
- buis.close();
- buos.close();
- }
- }
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |