Java的IO流实现目录拷贝

import java.io.*;
//拷贝整个目录和文件
public class CopyTest {
public static void main(String[] args) {
//指定拷贝的源目录和目标目录
File srcFile = new File(“E:/java”);
File destFile = new File(“F:\a\b\c”);
//调用拷贝方法
copyDirs(srcFile,destFile);
}
//定义拷贝方法
private static void copyDirs(File srcFile, File destFile) {
//取到传入源目录的子目录链表,如果数组是null,表示是文件
File[] files = srcFile.listFiles();
//对于文件直接进行读写
if(files==null){
FileInputStream fis=null;
FileOutputStream fos=null;
try {
fis = new FileInputStream(srcFile);
//目标路径的绝对路径应该就是源路径的相对路径和目标绝对路径的拼接,但是要考虑切换盘符
fos = new FileOutputStream((destFile.getAbsolutePath().endsWith("\")
?destFile.getAbsolutePath():destFile.getAbsolutePath()+"\")+
srcFile.getAbsolutePath().substring(3));
int readCount = 0;
//正常读写文件
byte[] bytes = new byte[1024 * 1024 * 10];
while((readCount=fis.read(bytes))!=-1){
fos.write(bytes,0,readCount);
}
fos.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return;
}
//到这里表示不是文件,创建目录
for(File file : files){
if(file.isDirectory()) {
//取得源目录的绝对路径
String src = file.getAbsolutePath();
//目标路径的绝对路径应该就是源路径的相对路径和目标绝对路径的拼接,但是要考虑切换盘符
String des = (destFile.getAbsolutePath().endsWith("\")
?destFile.getAbsolutePath():(destFile.getAbsolutePath()+"//"))+src.substring(3);
File newFile = new File(des);
//如果目标文件目录不存在,创建目录
if(!newFile.exists()){
newFile.mkdirs();
}
}
//进入递归,进入子目录中判断
copyDirs(file,destFile);
}
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值