java io 复制_JavaIO操作之复制整个文件夹

该博客详细介绍了如何使用Java编程实现从一个源文件夹到目标文件夹的完整复制功能,包括递归复制子文件夹及文件。在过程中,检查了源文件夹是否存在、是否为目录、目标文件夹是否已存在以及能否创建。代码中包含了处理文件和目录的复制方法,确保数据的完整迁移。
摘要由CSDN通过智能技术生成

static void cpyFolder(String source,String dest) {

//实现复制整个文件夹

File fs=null;

File fd=null;

//InputStream is=null;

//OutputStream os=null;

try {

if(source==null || dest ==null) {

throw new Exception("param :source Or dest incorrect!");

}

fs=new File(source);

fd=new File(dest);

if(!fs.exists()) {

throw new Exception("source file not exist!");

}

if(!fs.isDirectory()) {

throw new Exception("source file is not folder!");

}

if(fd.exists()) {

throw new Exception("dest file already exist!");

}

if(!fd.mkdirs()) {

throw new Exception("creat dest folder failed!");

}

cpyFold(fs,fd);

}

catch(Exception e) {

e.printStackTrace();

}

}

static void cpyFold(File s,File d) {

//复制的具体复制实现

if(s.isDirectory()) {

if(!d.exists()) {

if(!d.mkdirs()) {

System.out.println("MakeDir Failed!");

}

}

File[] tmp=s.listFiles();

for(int i=0;i

String

name=d.getAbsolutePath()+File.separator+tmp[i].getName();

System.out.println(name);

cpyFold(tmp[i],new File(name));

}

}

else {

if(!d.exists()) {

cpyFile(s,d);

}

}

}

static void cpyFile(File fs,File fd) { //复制单个文件

InputStream is=null;

OutputStream os=null;

try {

is=new FileInputStream(fs);

os=new FileOutputStream(fd);

byte[] buf=new byte[1024];

int n=0;

while(true) {

n=is.read(buf, 0, 1024);

if(-1==n)

break;

os.write(buf,0,n);

}

//System.out.println("COPY "+fs.getAbsolutePath()+" TO

"+fd.getAbsolutePath()+" OK!");

}

catch(Exception e) {

e.printStackTrace();

}

finally {

try {

if(null!=is ) {

is.close();

is=null;

}

if(null!=os) {

os.close();

os=null;

}

}

catch(IOException e) {

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值