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 :
- File.renameTo().
- 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(); } } }

my query is … how can i run this file movo java code in browser using javascript?
Hello i am very much interested in java and it’s technologies . i found lots of new things from your blog
how to upload file to a network drive in oracle 10g?
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.
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.
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!
Excellent Example
“renameTo” logic is good one……..
renameTo is a separate function?