A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 千山万水 中级黑马   /  2015-8-24 11:07  /  432 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

/*

* 需求:(把D盘文件复制到C盘)

*/

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

/*

思路

1、通过盘符或者盘符下的所以文件和目录。

2、对盘符下的文件进行遍历,遍历的过程中定义盘条件。

3、如果是文件,直接复制,如果是目录,那就对目录进行迭代。

4、如果目录中的文件还是目录,那就对目录进行递归操作。

5、关闭所有流资源。

*/

public class Test{

public static void main(String[] args)throws IOException{

copyRoot(new File("D:\\"),new File("C:\\"));

}

/*

复制文件方法

*/

public static void copyFile(File dest,File src)throws IOException{

InputStream ips = new FileInputStream(src);

OutputStream ops = new FileOutputStream(dest);

byte[] buf =new byte[1024];

int len = 0;

while((len = ips.read(buf))!=-1){

ops.write(buf, 0, len);

}

ips.close();

ops.close();

}

/*

复制目录下的文件。

*/

public static void copyDir(File dest,File src)throws IOException{

dest.mkdirs();

File []dirAndFile = src.listFiles();

for(File dirOrFile : dirAndFile){

if(dirOrFile.isFile()){

copyFile(new File(dest.getAbsolutePath()+"\\"+dirOrFile.getName()),

new File(dirOrFile.getAbsolutePath()));

}

else if(dirOrFile.isDirectory()){

copyDir(new File(dest.getAbsolutePath()+"\\"+dirOrFile.getName()),

new File(dirOrFile.getAbsolutePath()));

}

}

}

/*

复制整个盘符

*/

public static void copyRoot(File dest,File src)throws IOException{

File[] dirAndFile = src.listFiles();

if(src.exists()){

for(File dirOrFile : dirAndFile){

if(!dirOrFile.isHidden()){

if(dirOrFile.isFile()){

File destFile =

new File(dest.getAbsolutePath()+"\\"+dirOrFile.getName());

File srcFile =  

new File(src.getAbsolutePath()+"\\"+dirOrFile.getName());

copyFile(destFile,srcFile);

}

else if(dirOrFile.isDirectory()){

File destDir =  

new File(dest.getAbsolutePath()+"\\"+dirOrFile.getName());

File srcDir =

new File(src.getAbsolutePath()+"\\"+dirOrFile.getName());

copyDir(destDir,srcDir);

}

}

}

}

}
}

1 个回复

倒序浏览
我建议还是把 代码放在代码区里在放出来比较好~ 这样子毫无阅读性
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马