Wednesday, November 23, 2016

Move File from a Directory to Another Directory With Java

There's no move() method on Java's File class. But there's a renameTo() method. We can use this method to move files on Java.

Let's see how that works.

import java.io.File;

public class MoveFileTest {
    public static void main(String[] args) {
        File srcFile = new File("test/file.txt");
        File destFile = new File("test2/file.txt");

        srcFile.renameTo(destFile);
    }
}

The file file.txt should move from test directory to test2 directory.




Cross Platform Version:

The code I've written before was for Linux only. But if you want it to work on both Linux and Windows you can rewrite the program as follows.

import java.io.File;

public class MoveFileTest {
    public static void main(String[] args) {
        File srcFile = new File("test" + File.separator + "file.txt");
        File destFile = new File("test2" + File.separator + "file.txt");

        srcFile.renameTo(destFile);
    }
}



Cross Platform and Modular Version:

If you want a more modular and reusable version of the code, you can rewrite the program as follows.

import java.io.File;

public class MoveFileTest {
    public static void main(String[] args) {
        moveFile("file.txt", "test", "test2");
    }

    private static void moveFile(String name, String srcDir, String dstDir) {
        File srcFile = new File( srcDir + File.separator + name);
        File destFile = new File(dstDir + File.separator + name);

        srcFile.renameTo(destFile);
    }
}

Here I've created a method moveFile() to move files. Now I can just call the method whenever I want to move a file.

No comments:

Post a Comment