Move a file from one directory to another using java

Let’s learn to move a file from one directory to another using java.

Move a file from one directory to another using java

In java we can move file using Files.Path move() method. This method renames or moves file permanently.

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.

Throws:

UnsupportedOperationException
FileAlreadyExistsException
DirectoryNotEmptyException
IOException
SecurityException

Now let’s see an example on java move file.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaMoveFile
{
   public static void main(String[] args) throws IOException
   {
      Path move = Files.move(Paths.get("B:\flowerbrackets.txt"), Paths.get("B:\Softs\flowerbrackets.txt"));
      if(move != null)
      {
         System.out.println("File moved successfully");
      }
      else
      {
         System.out.println("Failed to move the file");
      }
   }
}


Output:

File moved successfully.


Also read – java overview