Move File in Java

If you want to move a file from one directory to anther in Java, you can use rename() method of File. The following is a simple code example for moving a file called “s1” to another directory.

package com.programcreek;
 
import java.io.File;
 
public class MoveFileExample {
 
	public static void main(String[] args) {
		File file = new File("/home/programcreek/Desktop/s1");
		String targetDirectory = "/home/programcreek/Desktop/d3/";
 
		if (file.renameTo(new File(targetDirectory+ file.getName()))) {
			System.out.println("File is moved to " + targetDirectory);
		} else {
			System.out.println("Failed");
		}
	}
}

Output:

File is moved to /home/programcreek/Desktop/d3/

Leave a Comment