实现:
1 import java.io.File;
2 import java.io.FileInputStream;
3 import java.io.FileOutputStream;
4 import java.io.IOException;
5
6 public class FileUtils {
7
8 //复制文件
9 public static void copyFile(File src, File dest) throws IOException{
10 if(!src.isFile()){
11 throw new RuntimeException(src.getPath() + "不存在");
12 }
13 FileInputStream fis = new FileInputStream(src);
14 FileOutputStream fos = new FileOutputStream(dest);
15
16 byte[] data = new byte[1024];
17 int len;
18 while((len = fis.read(data))!=-1){
19 fos.write(data, 0, len);
20 }
21
22 fos.close();
23 fis.close();
24 }
25
26 //复制文件夹
27 public static void copyDirectory(File srcDir,File destDir)throws IOException{
28 //父目录不能拷贝到子目录中
29 if(destDir.getAbsolutePath().contains(srcDir.getAbsolutePath())){
30 throw new IOException("父目录不能拷贝到子目录中");
31 }
32 if(!destDir.isDirectory()){
33 throw new IOException("目标对象不是目录");
34 }
35 File dest = new File(destDir,srcDir.getName());
36 //如果srcDir是个文件,那么直接复制文件到destDir中
37 if(srcDir.isFile()){
38 copyFile(srcDir, dest);
39 }else{
40 dest.mkdirs();//先在destPath目录中创建srcDir对应的文件夹
41 File[] list = srcDir.listFiles();//准备复制srcDir的子目录或子文件
42 for(File f: list){
43 copyDirectory(f,dest);
44 }
45 }
46 }
47 }
实现:
1 //剪切文件夹
2 public static void cutDirectory(File srcDir,File destDir)throws IOException{
3 if(destDir.getAbsolutePath().contains(srcDir.getAbsolutePath())){
4 throw new IOException("父目录不能剪切到子目录中");
5 }
6 if(!destDir.isDirectory()){
7 throw new IOException("目标对象不是目录");
8 }
9 File dest = new File(destDir,srcDir.getName());
10 if(srcDir.isFile()){
11 copyFile(srcDir, dest);
12 }else{
13 dest.mkdirs();
14 File[] list = srcDir.listFiles();
15 for(File f: list){
16 cutDirectory(f,dest);
17 }
18 }
19 srcDir.delete();
20 }
原文:https://www.cnblogs.com/niujifei/p/12284083.html