Move all files from folder to another folder using java

Possible duplicate:
Copy files from one directory to another in Java

How to transfer all files from one folder to another folder using java? I am using this code:

import java.io.File;

    public class Vlad {

        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here
            // File (or directory) to be moved
            File file = new File("C:\\Users\\i074924\\Desktop\\Test\\vlad.txt");

            // Destination directory
            File dir = new File("C:\\Users\\i074924\\Desktop\\Test2");

            // Move file to new directory
            boolean success = file.renameTo(new File(dir, file.getName()));
            if (!success) {
                System.out.print("not good");
            }
        }
    }

but it only works for one specific file.

thank!!!

+5
source share
4 answers

If the object Filepoints to a folder, you can iterate over the contents

File dir1 = new File("C:\\Users\\i074924\\Desktop\\Test");
if(dir1.isDirectory()) {
    File[] content = dir1.listFiles();
    for(int i = 0; i < content.length; i++) {
        //move content[i]
    }
}
+9
source

Using org.apache.commons.io. Fileutils class

moveDirectory(File srcDir, File destDir) we can move the whole directory

+12
source

Java 1.7 java.nio.file.Files, . move, copy walkFileTree.

+7
source
  • You can rename the directory itself.
  • You can iterate over files in a directory and rename them one by one. If the directory may contain subdirectories, you must do this recursively.
  • you can use a utility like Apache FileUtils that already does all this.
+1
source

All Articles