How to move file to another directory in Java

Java.io.File does not contains any ready make move file method, but you can workaround with the following two alternatives :

  1. File.renameTo().
  2. Copy to new file and delete the original file.

In the below two examples, you move a file “C:\\folderA\\Afile.txt” from one directory to another directory with the same file name “C:\\folderB\\Afile.txt“.

1. File.renameTo()


package com.mkyong.file;

import java.io.File;

public class MoveFileExample 
{
    public static void main(String[] args)
    {	
    	try{
    		
    	   File afile =new File("C:\\folderA\\Afile.txt");
    		
    	   if(afile.renameTo(new File("C:\\folderB\\" + afile.getName()))){
    		System.out.println("File is moved successful!");
    	   }else{
    		System.out.println("File is failed to move!");
    	   }
    	    
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    }
}

2. Copy and Delete


package com.mkyong.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MoveFileExample 
{
    public static void main(String[] args)
    {	
    	
    	InputStream inStream = null;
	OutputStream outStream = null;
		
    	try{
    		
    	    File afile =new File("C:\\folderA\\Afile.txt");
    	    File bfile =new File("C:\\folderB\\Afile.txt");
    		
    	    inStream = new FileInputStream(afile);
    	    outStream = new FileOutputStream(bfile);
        	
    	    byte[] buffer = new byte[1024];
    		
    	    int length;
    	    //copy the file content in bytes 
    	    while ((length = inStream.read(buffer)) > 0){
    	  
    	    	outStream.write(buffer, 0, length);
    	 
    	    }
    	 
    	    inStream.close();
    	    outStream.close();
    	    
    	    //delete the original file
    	    afile.delete();
    	    
    	    System.out.println("File is copied successful!");
    	    
    	}catch(IOException e){
    	    e.printStackTrace();
    	}
    }
}

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
stephanep
Guest
stephanep

15 lines just to move a file from a folder to another folder !!!

I’m exhausted just by looking at the code…

I can’t understand what was in Sun engineers mind when they created that spaghetti dish of a language.

nagar
Guest
nagar

how to copy a file from one folder to another
using sftp protocol in java

gnanavelu
Guest
gnanavelu

need your assistance to navigate different directory in unix using java program

revathi muthu krishnan
Guest
revathi muthu krishnan

Dear Mkyong,

Whether “C:\folderA\Afile.txt” can be saved in String named text and this text can be called in File like

File afile =new File(text);
this is possible?

revathi muthu krishnan
Guest
revathi muthu krishnan

This can be achieved thro’ JSP?If so please share the Codes

saji
Guest
saji

tnx guys!!!

Goms
Guest
Goms

Hi same code is not working for FTP server,
I want to move some zip files from FTP server to local drive.

bial
Guest
bial
i used this [[ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package copy; /** * * @author Dev1 */ import java.io.File; public class Copy { /** * @param args the command line arguments */ public static void main(String[] args) { try{ File afile =new File(“C:\9.txt”); if(afile.renameTo(new File(“C:\hi\9.txt” + afile.getName()))){ System.out.println(“File is moved successful!”); }else{ System.out.println(“File is failed to move!”); } }catch(Exception e){ e.printStackTrace(); } } } ]]
kk
Guest
kk

43434

bial
Guest
bial

hi i used the same code but it is saying that “nothing to copy”

Guest
Guest
Guest

Now-a-days you will want to use this:

“Files.move(source, target, REPLACE_EXISTING);”

hikingmike
Guest
hikingmike

I think this will not move files between drives. Nevermind, it does for me.

Aamir Ali
Guest
Aamir Ali

my code is this

File wallpaperDirectory3 = new File(“/sdcard/Download/Scan1.jpg”);

boolean success = wallpaperDirectory3.renameTo(new File(

wallpaperDirectory, wallpaperDirectory3.getName()));

Toast.makeText(getApplicationContext(), “” + success, Toast.LENGTH_LONG)

.show();

Aamir Ali
Guest
Aamir Ali

hi i used this code to move file from one directory to another in android, but it is not working

visitor
Guest
visitor

why not using “java.nio.file.StandardCopyOption” ?

well I’m looking for easy and effective way for moving whole folder to other location(can be on different filesystem or the same one) and found the “Files.move()” method from the Java documentation

wffger
Guest
wffger

You cannot import it in Android.

vyshu
Guest
vyshu

did the same code works for android emulator?

Stefan Dietiker
Guest
Stefan Dietiker

Indeed, there’s an API to move files:

http://docs.oracle.com/javase/tutorial/essential/io/move.html

jo
Guest
jo

I have two files in the directory, the first one fails but the second is successful when using renameTo. Why is it like that?

Alket
Guest
Alket

Hi, thanks for the information about java in your web site! Great work!

Mwesigye John Bosco
Guest
Mwesigye John Bosco

You saved me Boss!!!!!!!!!!!!!!!!!!.You have the best solution i was looking for

Mr.Help
Guest
Mr.Help

Can you copy a File Video…Example: copy a video From C:\\ To D:\\ (OS)

Mwesigye John Bosco
Guest
Mwesigye John Bosco

hi i tried to copy an image and video files using the same code and it worked.

Aufar Sukmajaya
Guest
Aufar Sukmajaya

mkyong, god bless you @_@

Ravinath
Guest
Ravinath

Thanks very helpfull

ArunKongara
Guest
ArunKongara

Hi mkyong

i have files few files in dir Screenshots i want to create new Dir in screenshots and move all files to that dir . how we can achieve this

Thanks in advance

ArunKongara

Jay Joshi
Guest
Jay Joshi

my query is … how can i run this file movo java code in browser using javascript?

Jay Joshi
Guest
Jay Joshi

Hello i am very much interested in java and it’s technologies . i found lots of new things from your blog

Jesslyn
Guest
Jesslyn

how to upload file to a network drive in oracle 10g?

akhil kumar
Guest
akhil kumar

hello sir
it’s to move a text file.
How can i move a file other than .txt ?
like .RAR , or any video/audio file.

Ananth
Guest
Ananth

Good exercise. In the copy & delete example, it would be good to use “deleteOnExit()”. If we use “delete()” the source file might be still in use and may not get deleted.

Thanks.

missserena
Guest
missserena

Thanks for this tutorial. I gave this a shot such that I am calling it in a loop and iterating over serveral files in a directory to be moved to a new location. It did the move of all the files perfectly. However, only one file was actually deleted. Is there something that must be added in order to get it to delete the files in the source directly with successive calls to this function? Your thought would be much appreciated.

Cheers!

Harish Chand
Guest
Harish Chand

Excellent Example

pradip garala
Guest
pradip garala

“renameTo” logic is good one……..

mmmm
Guest
mmmm

renameTo is a separate function?

visitor
Guest
visitor

“renameTo” only works if the source and destination is in the same filesystem (same drive if on pc, same storage if on mobile)

sers
Guest
sers

I’ve just successfully copied a file from disk D: to disc C:

Jun Jie Gan
Guest
Jun Jie Gan

perhaps ur disk C and D is separated by logical partition
and they still running on the same harddrive