5

Possible Duplicate:
Copying files from one directory to another in Java

How can I move all files from one folder to other folder with java? I'm 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 is working only for one specific file.

thanks!!!

Community
  • 1
  • 1
vlio20
  • 8,955
  • 18
  • 95
  • 180

4 Answers4

13

By using org.apache.commons.io.FileUtils class

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

NPKR
  • 5,368
  • 4
  • 31
  • 48
12

If a File object points to a folder you can iterate over it's content

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]
    }
}
André Stannek
  • 7,773
  • 31
  • 52
7

Since Java 1.7 there is java.nio.file.Files which offers operations to work with files and directories. Especially the move, copy and walkFileTree functions might be of interest to you.

Robert Kühne
  • 898
  • 1
  • 12
  • 33
1
  • You can rename the directory itself.
  • You can iterate over files in directory and rename them one-by-one. If directory can contain subdirectories you have to do this recursively.
  • you can use utility like Apache FileUtils that already does all this.
beat
  • 1,857
  • 1
  • 22
  • 36
AlexR
  • 114,158
  • 16
  • 130
  • 208