将指定的文件或目录拷贝到指定目录夹下
import java.io.*;
import java.util.Scanner;/*** 实现一个文件拷贝*/
public class FileCopy {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.println("请输入要拷贝的源文件路径:");String srcPath = scanner.next();System.out.println("请输入要拷贝的目标文件路径:");String destPath = scanner.next();File src = new File(srcPath);File dest = new File(destPath);process(src,dest);System.out.println("拷贝完成!!!");}/*** 进行文件拷贝* @param src 源文件* @param dest 目标文件*/public static void process(File src, File dest) {// 判断源文件是否为文件if(src.isFile()){// 将源文件直接拷贝到目标文件夹下try(FileInputStream fileInputStream = new FileInputStream(src);FileOutputStream fileOutputStream = new FileOutputStream(dest +"\\" + src.getName() );){byte[] bytes = new byte[1024];int len = 0;while((len = fileInputStream.read(bytes)) != -1){fileOutputStream.write(bytes, 0, len);}fileOutputStream.flush();}catch (IOException e){System.out.println("出错了!!!");}// 结束递归return;}// 执行到这里说明不是文件,是目录File newFile = new File(dest.getPath() + "\\" + src.getName());if(!newFile.exists()){newFile.mkdirs();}// 得到目录下的所有文件File[] files = src.listFiles();for (File file : files) {process(file, newFile);}}}
结果