import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Toolclass {
// f1为对象文件路径,f2为目标文件路径
public static void copyfloder(File f1, File f2) throws IOException {
if (f1.isDirectory()) {
File newfile = new File(f2, f1.getName());
// 如果路径不存在创建一个路径
newfile.mkdirs();
File[] filearr = f1.listFiles();
for (File ff : filearr) {
copyfloder(ff, newfile);
}
} else {
File newFile = new File(f2, f1.getName());
copyfiles(f1, newFile);
}
}
private static void copyfiles(File file1, File file2) throws IOException {
// 创建输入输出流缓冲区
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file1));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file2));
byte[] bys = new byte[1024];
int len = 0;
// 读取源目标路径文件内容
while ((len = bis.read(bys)) > 0) {
bos.write(bys, 0, len);
}
bis.close();
bos.close();
}
}
--------------------------------测试类-------------------------------------------------------------------------
package com.shikun.tool;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class TestTool {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//封装文件对象
String path1="";
String path2="";
Scanner sc=new Scanner(System.in);
System.out.print("源文件路径:");
path1=sc.nextLine();
System.out.print("目标文件路径:");
path2=sc.nextLine();
File f1=new File(path1);
File f2=new File(path2);
Toolclass.copyfloder(f1, f2);
System.out.println("复制完成");
sc.close();
}
}