java--基础---复制文件夹及其中的文件

代码:

package com.io.demo;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;


public class copyDir {


public static void main(String[] args) {
copyDir("d:/a","d:/b");
}

/**
* 复制文件夹
*/
private static void copyDir(String srcRoot,String srcDir,String destDir){
if(srcRoot == null){
srcRoot = srcDir ;
}
//源文件夹
File srcFile = new File(srcDir);
//目标文件夹
File destFile = new File(destDir);

//判断srcFile有效性
if(srcFile == null || !srcFile.exists()){
return ;
}
//创建目标文件夹
if(!destFile.exists()){
destFile.mkdirs();
}

//判断是否文件?
if(srcFile.isFile()){
String absPath = srcFile.getAbsolutePath() ;
//取出上级目录 d:
String parentDir = new File(srcRoot).getParent();

//取出相对的路径
String relPath = absPath.substring(parentDir.length());
File destFile2 = new File(destDir,relPath);
//拷贝文件
copyFile(srcRoot,srcFile.getAbsolutePath(),destDir);
}
//目录
else{
File[] children = srcFile.listFiles();
if(children != null){
for(File f : children){
copyDir(srcRoot,f.getAbsolutePath(),destDir);
}
}
}
}

public static void copyDir(String srcDir,String destDir){
copyDir(srcDir,srcDir,destDir);
}
/**
* 复制文件
*/
public static void copyFile(String srcRoot,String path,String destDir){
try {

//准备目录
//取出相对的路径
String tmp = path.substring(srcRoot.length());
String folder = new File(destDir,tmp).getParentFile().getAbsolutePath();
System.out.println(folder);
File destFolder = new File(folder);
destFolder.mkdirs();

File f = new File(path);
//fis
FileInputStream fis = new FileInputStream(path);

String newDestpath = null ;
//文件输出流
FileOutputStream fos = new FileOutputStream(new File(destFolder,new File(path).getName()));

//流的对拷贝
byte[] buf = new byte[1024] ;
int len = 0 ;
while((len = fis.read(buf)) != -1){
fos.write(buf, 0, len);
}
fis.close();
fos.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值