把一个文件复制到另一个文件下

来源:互联网 发布:网络推广公司赚钱吗 编辑:程序博客网 时间:2024/05/16 11:02
import java.io.*;


public class CopyDir
{
public static void main(String[] args){
//封装要复制的目录
File file = new File("D:\\dest");
//调用方法完成复制
copyFile(file);
}
//复制方法
public static void copyFile(File file){

//递归需要结束条件,结束条件就是,如果这个文件不是目录了,是一个普通的文件递归结束。
if(file.isFile()){
//如果是一个文件我们才考虑复制
//复制粘贴之后的路径还没有,我们需要创建目录
String srcFileParentPath = file.getParent();
//复制到C盘根目录下
String destFileParentPath = "C" + srcFileParentPath.substring(1);
//如果目录不存在创建
File destParentFile = new File(destFileParentPath);
if(!destParentFile.exists()){
destParentFile.mkdirs();
}
//复制文件一边读,一边写
FileInputStream fis = null;
FileOutputStream fos = null;
try{
fis = new FileInputStream(file);
fos = new FileOutputStream("C" + file.getAbsolutePath().substring(1));//从第地址1开始截取


byte[] bs = new byte[100*1024]; //100KB
int readCount = 0;
while((readCount=fis.read(bs))!=-1){
fos.write(bs,0,readCount);
}


fos.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
if(fos!=null){
try{
fos.close();
}catch(Exception e){
e.printStackTrace();
}
}
if(fis!=null){
try{
fis.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
return;
}


//先把file看做目录。
File[] fs = file.listFiles();


//遍历子文件
for(File subFile:fs){
//subFile可能是一个文件也可能是一个目录。
System.out.println(subFile.getAbsolutePath());
copyFile(subFile);
}
}
}
原创粉丝点击