如何在Java中将特定文件移动到新文件夹

时间:2019-07-11 16:48:01

标签: java file move

我想将文件名为FGA的4个文件移动到新文件夹中

public void delete(String DirectoryName) {
         String dir = DirectoryName;

         File file = new File(dir);

         boolean recursive = true;

         Collection files = FileUtils.listFiles(file, null, recursive);

         for (Iterator iterator = files.iterator(); iterator.hasNext();) {
                File file1 = (File) iterator.next();
                if (file1.getName().contains("FGA_"))
                      file1.delete();
                else if (file1.getName().contains("UPP_"))
                      file1.delete();

         }
         System.out.println("Files deleted");
   }

1 个答案:

答案 0 :(得分:2)

我确实看到您正在使用commons.apache.org库,因此您可以从那里使用moveFile

public static void moveFile(File srcFile,
        File destFile)
                 throws IOException

或来自jdk Files

public static Path move​(Path source,
                    Path target,
                    CopyOption... options)
             throws IOException

这是您使用apache commons进行的代码更改

 for (Iterator iterator = files.iterator(); iterator.hasNext();) {
            File file1 = (File) iterator.next();
            if (file1.getName().contains("FGA_"))
                  FileUtils.moveFile(file1, new File("destination"));
            else if (file1.getName().contains("UPP_"))
                  FileUtils.moveFile(file1, new File("destination"));
     }