Moving a file from one directory to another using Java

Course Curriculum

Moving a file from one directory to another using Java

Moving a file from one directory to another using Java

Java provides functions to move files between directories. Two ways to achieve this are described here. The first method utilizes Files package for moving while the other method first copies the file to destination and then deletes the original copy from the source.

Using Files.Path move() method: Renaming and moving the file permanently to a new location.
Syntax:
public static Path move(Path source, Path target, CopyOption..options)
throws IOException
Parameters:
source - the path to the file to move
target - the path to the target file
(may be associated with a different provider to the source path)
options - options specifying how the move should be done
Returns: the path to the target file

// Java program to illustrate renaming and
// moving a file permanently to a new loaction
import java.io.*;
import java.nio.file.Files;
import java.nio.file.*;

public class Test
{
public static void main(String[] args) throws IOException
{
Path temp = Files.move
(Paths.get("C:Usersfile.txt"),
Paths.get("C:Usersfile2.txt"));

if(temp != null)
{
System.out.println("File renamed and moved successfully");
}
else
{
System.out.println("Failed to move the file");
}
}
}
Output:

File renamed and moved successfully
Using Java.io.File.renameTo() and Java.io.File.delete() methods: Copying the file and deleting the original file using these two methods.
Syntax of renameTo():
public boolean renameTo(File dest)
Description: Renames the file denoted by this abstract path name.
Parameters: dest - The new abstract path name for the named file
Returns: true if and only if the renaming succeeded; false otherwise
Syntax of delete():

public boolean delete()
Description: Deletes the file or directory
denoted by this abstract path name.
Returns: true if and only if the file or
directory is successfully deleted; false otherwise

// Java program to illustrate Copying the file
// and deleting the original file
import java.io.*;

public class Test
{
public static void main(String[] args)
{
File file = new File("C:Users1.txt");

// renaming the file and moving it to a new location
if(file.renameTo
(new File("C:UsersnewFile.txt")))
{
// if file copied successfully then delete the original file
file.delete();
System.out.println("File moved successfully");
}
else
{
System.out.println("Failed to move the file");
}

}
}
Output

File moved successfully

(Next Lesson) How to start learning Java