Moving a file from One Directory to Another using Java

Hey Folks,

You must have moved your files from one directory to another number of times, but have you done it with the help of Java?

If not, then let’s learn it today. Here I am going to tell you how to move a file in Java.

First of all, we must know there is no direct Java File method for this purpose.

But there is one another method for renaming a file in Java. Now you might think how can a method used for renaming files be beneficial for this purpose.



Let’s see this by learning about the Java File.renameTo() method

Java File.renameTo() method

This method is used to primarily used to rename a certain file.

Syntax:

File.renameTo(file destination)

This method true if the renaming is successful otherwise it returns false.

Now what we will do to move the file in Java is, provide the path in method parameter with the same name, which will result in moving the file from our original directory to our destination directory with the same name.

Here is how our final Java code will look like.

import java.io.*;
public class test
{
  public static void main(String[] args)
  {
           File file =new File("E:\\Test\\prog.txt");
    
 	   if(file.renameTo(new File("E:\\Exam\\" + file.getName())))
 	   {
 		System.out.println("Your file has been moved!");
 	   }
 	   else
 	   {
 		System.out.println("Unable to move the file, please check the file path and file name correctly");
 	   }
  }
}

In the above example, we are initially having our file in the E drive inside Test directory. We wish to move our file to the Exam directory in the same drive.

In the above code, we are using a method file.getName(), this method is used for getting the last name of the pathname’s name sequence, that means the name of the file or directory.

After execution of the above code, we will receive the following output.

OUTPUT:

Your file has been moved!

There is another way to perform this task, that is by first copying the file into our desired directory and then deleting the file from the initial directory. But this requires writing more code and is also not memory efficient as compared to the method we are using. Therefore we will stick to this code.

Also, read:

 

Do let me know in the comments section if you have any doubts.

Happy Coding 🙂

 

Leave a Reply

Your email address will not be published. Required fields are marked *