java 复制文件夹及其子文件_用Java程序实现文件夹及其子文件拷贝的小例子

package com.hugo;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

public class Copy {

//设置成静态常量,方便方法中调用

static String from = null;

static String to = null;

public static void main(String[] args) {

from = "h:\\a";

to = "f:\\b";

new Copy(from);

}

// 实现文件夹及文件的拷贝

public Copy(String str) {

File file = new File(str);

File[] files = file.listFiles();

for (File f : files) {

String a = f.getAbsolutePath();

if (f.isDirectory()) {

new Copy(a);// 再次判断是否为文件,递归

} else {

File b = new File(a.replace(from, to));// 路径转换,例,d:/a/b/c.txt 把from(d:/a)换成to(e:/b)-->e:/b/b/c.txt

File c = new File(b.getParent());// 获得目标文件的路径

c.mkdirs();// 创建目标文件路径的文件夹

copyFile(f, b);// 调用文件拷贝

}

}

}

// 文件的拷贝(文件源,目标文件)

public void copyFile(File src, File des) {

FileInputStream reader = null;

FileOutputStream out = null;

try {

reader = new FileInputStream(src);

out = new FileOutputStream(des);

byte[] bs = new byte[1024 * 1024 * 10];//10兆的字节数组

int i = 0;

try {

while ((i = reader.read(bs)) != -1) {

out.write(bs, 0, i);

}

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} finally {// 注意关闭流

if (reader != null) {

try {

reader.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

if (out != null) {

try {

out.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值