How to Move File From One Directory to Another in Java


In this example we will show how to move a file from one directory to another in Java.

Source Code

package com.beginner.examples;

import java.io.*;

public class FileOperator15Example { 
	public static void main(String[] args )
    {	
		try
        {
        	 File path = new File("example.txt");
        	 if (!path.exists()) 
        	 {
        		 path.createNewFile();
        	 }
        	 
        	 File newName = new File("d:/test.txt");
        	 path.renameTo(newName);
        	 System.out.println("Move succesful!");
        } 
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

Output:

Move succesful!
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments