1.文件及文件夹路径
在G盘中有一个新建文件夹,其中有一个a文件夹和一张图片,在a文件夹中有b文件夹和一个吧"b.txt"文件,在b文件夹中有一个"c.txt"文件,两个文件均有内容。
2.代码
package com.igeek;
import java.io.*;
/**
* @Author:
* @ClassName:
* @Description:copy
* @Date: Create in 16:17 2021/4/18
*/
public class CopyFile {
public static void main(String[] args) throws IOException {
File src = new File("G:\\新建文件夹");//源文件
File dest = new File("F:\\");//目标文件
copyMethod(src,dest);//复制方法
}
public static void copyMethod(File src,File dest) throws IOException {
File[] frr1 = src.listFiles();//创建File数组
for (File f : frr1){
if (f.isDirectory()){
String s1 = f.getName();
String s2 = dest.getAbsolutePath();//获取目标文件绝对路径
String s3 = s2+"\\"+s1;
File f1 = new File(s3);
f1.mkdir();
copyMethod(f,f1);//递归
}else {
String s4 = f.getName();
String s5 = dest.getAbsolutePath();
String s6 = s5+"\\"+s4;
File f2 = new File(s6);
copyFile(f,f2);//文件复制方法
}
}
}
public static void copyFile(File src , File dest) throws IOException {
//使用的时字节流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dest));
int len = -1;
while ((len = bis.read())!= -1){
bos.write(len);
}
bos.close();
bis.close();
}
}
3.此代码比较简陋,并没有判断文件夹是否为空,目标文件夹下是否有相同的文件或文件夹,下次更正