How to move file to another directory in java

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.

In below example, we will move config_new.properties from /Users/Arpit/Desktop/Folder1 to /Users/Arpit/Desktop/Folder2 .

Java Program:

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("-----------------");

 }

}

When I ran above program, I got following output:
-----------------
Move operation is successful
-----------------
Move operation is unsuccessful
-----------------

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012