To migrate any file in Java, in Java 6 or older Java versions, we can use the renameTo() method located in the File object to do this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.huongdanjava.javaexample; import java.io.File; public class MoveFile { public static void main(String[] args) { File source = new File("F://source.txt"); File dest = new File("E://dest.txt"); if (source.renameTo(dest)) { System.out.println("Move file " + source.getAbsolutePath() + " to " + dest.getAbsolutePath() + " success."); } } } |
Result:
1 |
Move file F:\source.txt to E:\dest.txt success |
From Java 7 onwards, we have another way to move a file, which is to use the Files object. This Files object contains all the methods that make it possible to perform all file-related operations such as creating files, deleting files, copying files or moving files, etc. Below is the code to move a file with Files object:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.huongdanjava.javaexample; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class MoveFile { public static void main(String[] args) throws IOException { Path source = Paths.get("F://source.txt"); Path dest = Paths.get("E://dest.txt"); Files.move(source, dest); } } |
And like copying files, we can even use the Apache Commons IO library to move a file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.huongdanjava.javaexample; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; public class MoveFile { public static void main(String[] args) throws IOException { File source = new File("F://source.txt"); File dest = new File("E://dest.txt"); FileUtils.moveFile(source, dest); } } |