如何用java代码实现文件夹的递归复制和复制文件
1、定义一个变量用来存放复制的文件数量
static int size=0;//确定这个文件夹共有多少个文件
2、写一个基本的处理步骤
1、检查路径是否可达
2.、判断所在文件夹是否相同,以便于确定是否在文件是否重复
3、判断是否为文件夹,或者文件,如果是文件的话,就直接进行复制
4、递归的调用
3、java代码进行实现
1、这一部分是组要介绍大致的框架
//复制函数
static void dirCopy(String src_abspath,String dest_abspath) throws IOException {
File path1 = new File(src_abspath);
File path2 = new File(dest_abspath);
//1.检查路径是否可达
//(代码过多就省略展示了)
//2.判断所在文件夹是否相同
if(!path1.getPath().equals(path2.getPath())) {
//3.判断是否是文件夹或者是文件
if(path1.isFile()) {
path2 = new File(path2.getPath()+"/"+path1.getName());
copyFile(path1, path2);//复制文件的部分,代码在下面
return ;
}else {
//4.递归调用
function1(path1, path2);//进行递归的部分,代码在下面
}
}else {
return ;
//(代码过多就省略展示了,这一部分是复制的路径和源文件的路径相同的情况下)
}
2、这一部分是实现递归函数的部分
//建立递归函数
private static void function1(File file1,File file2) throws IOException {
if(file1==null||!file1.exists()) {
return; //递归头
}else { //递归体
if(file1.isFile()) {
//如果是直接修改file2的话,会影响下一次的循环中的file2,所以我建立新的file3
File file3 = new File(file2.getPath()+"/"+file1.getName());
//这一步必须执行,否者找不到文件
file3.createNewFile();
copyFile(file1, file3); //复制代码
}else {
//每次根深层次的复制的时候,必须提前将两个file对象的进行同步
file2 = new File(file2.getPath()+"/"+file1.getName());
file2.mkdirs();
for (File file : file1.listFiles()) {
function1(file, file2);
}
}
}
}
3、IO流进行操作:文件复制
//复制文件
static void copyFile(File file1,File file2) {
OutputStream os=null;
InputStream is = null;
try {
os = new FileOutputStream(file2);
is = new FileInputStream(file1);
byte[] b = new byte[1024*4];
int item = -1;
while((item = is.read(b))!=-1) {
os.write(b, 0, item);
}
os.flush();
size++;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(is!=null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(os!=null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
4、执行的结果
public static void main(String[] args) throws IOException {
dirCopy("E:/qq文件/190517","D:/copy");
System.out.println("文件数:"size);
}
文件数: 169