您的位置:首页 > 编程语言 > Java开发

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

2016-08-14 12:21 260 查看
代码:

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);
<
4000
/span>}
/**
* 复制文件
*/
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();
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: