java 复制目录_Java 目录拷贝

该博客详细介绍了如何使用Java实现文件及目录的拷贝操作,包括递归处理子目录和文件的拷贝,以及在不同目录结构下创建目标文件夹。通过FileInputStream和FileOutputStream进行文件内容的读写,并确保文件的正确流转和关闭。
摘要由CSDN通过智能技术生成

import java.io.*;

/**

* 目录拷贝

*/

public class CopyAll {

public static void main(String[] args) {

File srcFile = new File("D:\\StudySource\\Java\\powernode\\文本笔记");

File destFile = new File("F:\\Java 目录拷贝\\");

copyAll(srcFile, destFile);

}

private static void copyAll(File srcFile, File destFile) {

if (srcFile.isFile()) {

// 是文件,递归结束,开始拷贝

FileInputStream in = null;

FileOutputStream out = null;

try {

// in = new FileInputStream(srcFile.getAbsoluteFile());

// 或者这么写

in = new FileInputStream(srcFile);

byte[] bytes = new byte[1024 * 1024];

out = new FileOutputStream((destFile.getAbsolutePath().endsWith("\\") ?

destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\" )

+ srcFile.getAbsolutePath().substring(3));

int readCount = 0;

while((readCount = in.read(bytes)) != -1){

out.write(bytes,0, readCount);

}

out.flush();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

if (out != null) {

try {

out.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (in == null) {

try {

in.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

return;

}

File[] files = srcFile.listFiles();

// 如果是目录,则需要对应新建目录

for (File f : files) {

if (f.isDirectory()){

String srcDir = f.getAbsolutePath(); // 原文件绝对路径

String srcDir2 = srcDir.substring(3); //截掉前面的盘符

// 这里是因为有时候复制到 F:\\ 和 F:\\a\\b\\ 下读取的绝对路径不一样

String destDir = (destFile.getAbsolutePath().endsWith("\\") ?

destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\" )

+ srcDir2;

// 新建一个 File 对象

File newFile = new File(destDir);

// 目录不存在,则以多重目录的方式新建目录

if (!newFile.exists()){

newFile.mkdirs();

}

}

// 递归

copyAll(f, destFile);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值