In this post, we will see how to move file to another directory in java. We will use java.io.File ‘s rename(File dest) to do it.
When I ran above program, I got following output:
In below example, we will move config_new.properties from /Users/Arpit/Desktop/Folder1 to /Users/Arpit/Desktop/Folder2 .
Java Program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package org.arpit.java2blog; import java.io.File; /* * @Author : Arpit Mandliya */ public class MoveFileMain { public static void main(String[] args) { System.out.println("-----------------"); //when source file is present File fileSrc = new File("/Users/Arpit/Desktop/Folder1/config_new.properties"); File newFileDest = new File("/Users/Arpit/Desktop/Folder2/"+fileSrc.getName()); if(fileSrc.renameTo(newFileDest)){ System.out.println("Move operation is successful"); }else{ System.out.println("Move operation is unsuccessful"); } System.out.println("-----------------"); //when source file is not present File file = new File("/Users/Arpit/notExists.txt"); File newFile = new File("xyz.txt"); if(file.renameTo(newFile)){ System.out.println("Move operation is successful"); }else{ System.out.println("Move operation is unsuccessful"); } System.out.println("-----------------"); } } |
1 2 3 4 5 6 7 |
----------------- Move operation is successful ----------------- Move operation is unsuccessful ----------------- |
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.