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

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);
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值