(转)文件或文件夹拷贝(源代码)
原文载于:http://www.blogjava.net/web/
//任务:
//写一个文件拷贝函数:?fileCopy(String?a?,String?b)???
//a--表示原文件名???b--表示目标文件名扩展:
//如果a是文件,则copy?a到b?;
//如果a是目录,则递归copy?a下的所有文件和文件夹(包括子文件夹)到b目录下。
//
import?java.io.*;
public?class?IODemo?{
????
????public?void?fileCopy(String?a,?String?b){
????????File?file?=?new?File(a);
????????if(!file.exists()){
????????????System.out.println(a?+?"?Not?Exists.");
????????????return;
????????}
????????File?fileb?=?new?File(b);
????????if(file.isFile()){
????????????FileInputStream?fis?=?null;
????????????FileOutputStream?fos?=null;
????????????try?{
????????????????fis?=?new?FileInputStream(file);
????????????????fos?=??new?FileOutputStream(fileb);
????????????????
????????????????byte[]?bb?=new?byte[?(int)file.length()];
????????????????fis.read(bb);
????????????????fos.write(bb);
????????????}catch?(IOException?e){
????????????????e.printStackTrace();
????????????}finally{
????????????????try?{
????????????????????fis.close();
????????????????????fos.close();
????????????????}?catch?(IOException?e)?{
????????????????????e.printStackTrace();
????????????????}
????????????}
????????}else?if(file.isDirectory()){
????????????if(!fileb.exists()){
????????????????fileb.mkdir();
????????????}
????????????String[]?fileList;
????????????fileList?=?file.list();
????????????for(int?i?=?0;?i?<?fileList.length;?i++){
????????????????fileCopy(a?+?"\\"?+?fileList[i],b?+?"\\"?+?fileList[i]);
????????????}
????????}
????}
????
}
?
?