获得文件列表,文件移动

 1 package file;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.util.ArrayList;
 8 import java.util.List;
 9 
10 import org.apache.commons.lang3.StringUtils;
11 
12 public class fileListAndMove {
13 
14     public static void main(String[] args) {
15         String strPath = "D:\\文件\\手机app";
16         String newPath = "D:/等等";
17         List<File> filelist = new ArrayList<>();
18         for (File f : getFileList(strPath, filelist)) {
19             System.out.println(f);
20             removeFile(f, strPath, newPath);
21         }
22     }
23 
24     /**
25      *     获得文件列表
26      * @param strPath
27      * @param filelist
28      * @return
29      */
30     public static List<File> getFileList(String strPath, List<File> filelist) {
31         File dir = new File(strPath);
32         File[] files = dir.listFiles(); // 该文件目录下文件全部放入数组
33         if (files != null) {
34             for (int i = 0; i < files.length; i++) {
35                 if (files[i].isDirectory()) {
36                     getFileList(files[i].getAbsolutePath(), filelist); // 遍历子文件夹里面的东西
37                 } else {
38                     filelist.add(files[i]);
39                 }
40             }
41         }
42         return filelist;
43     }
44 
45     /**
46      *     文件移动
47      * @param f
48      * @param strPath
49      * @param newPath
50      */
51     @SuppressWarnings("unused")
52     private static void removeFile(File f, String strPath, String newPath) {
53         // 定义移动后的文件路径
54         File bfile = new File(
55                 StringUtils.join(newPath, "//", f.getAbsolutePath().toString().substring(strPath.length())));
56         try {
57             if (!bfile.exists()) {
58                 // 先得到文件的上级目录,并创建上级目录,在创建文件
59                 bfile.getParentFile().mkdir();
60                 bfile.createNewFile();
61             }
62 
63             FileInputStream c = new FileInputStream(f);
64             FileOutputStream d = new FileOutputStream(bfile);
65             byte[] date = new byte[512];// 定义byte数组
66             int i = 0;
67             while ((i = c.read(date)) > 0) {// 判断是否读到文件末尾
68                 d.write(date);// 写数据
69             }
70             c.close();// 关闭流
71             d.close();// 关闭流
72 //            afile.delete();// 删除原文件
73             System.err.println("文件移动成功:" + bfile);
74         } catch (IOException e) {
75             e.printStackTrace();
76         }
77     }
78 }

猜你喜欢

转载自www.cnblogs.com/rfzhu/p/11636426.html