package fuzhi;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
//请输入源文件或文件夹的路径 和目标路径,完成文件或文件夹的复制
public class FuZhi {
public static void main(String[] args) throws IOException {
System.out.println("请输入源文件或目录的路径:");
Scanner sc = new Scanner(System.in);
String src = sc.nextLine();
System.out.println("请输入目标路径:");
String dest = sc.next();
//创建源文件或目录的对象
File srcFile = new File(src);
//创建目标路径对象
File destFile = new File(dest);
//调用copy 方法完成复制
copy(srcFile,destFile);
System.out.println("复制完毕!");
}
private static void copy(File srcFile, File destFile) throws IOException {
if(srcFile.isDirectory()) {
String name = srcFile.getName();
File newFile = new File(destFile,name);
newFile.mkdirs();
//获取源目录里的内容
File[] files = srcFile.listFiles();
//遍历源目录内容
for (File f : files) {
copy(f,newFile);
}
}else {
String name = srcFile.getName();
File newFile = new File(destFile,name);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
byte[] b = new byte[1024];
int len = -1;
while((len=bis.read(b)) != -1) {
bos.write(b, 0, len);
bos.flush();
}
bos.close();
bis.close();
}
}
}
|
|