Java - File Input Output Move Files

Introduction

The move(Path source, Path target, CopyOption... options) method moves or renames a file.

The move operation fails if the specified target file already exists.

You can specify the REPLACE_EXISTING option to replace the existing target file.

If the file to move is a symbolic link, it moves the symbolic link, not the target of the symbolic link.

The move() method can only be used to move an empty directory.

A DirectoryNotEmptyException is thrown if the directory is not empty.

You can use the ATOMIC_MOVE as another CopyOption.

If ATOMIC_MOVE option is specified, all other options are ignored.

The following code shows how to move a file by handling possible exceptions:

Demo

import java.io.IOException;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class Main {
  public static void main(String[] args) {
    // Create source and target paths using the syntax supported by your
    // platform/*from   w ww .  j av  a2s . c  o  m*/
    Path source = Paths.get("C:\\myData\\Main.java");
    Path target = Paths.get("C:\\myData\\dir2\\Main.java");

    try {
      // Try moving the source to target atomically
      Path p = Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
      System.out.println(source + " has been moved to " + p);
    } catch (NoSuchFileException e) {
      System.out.println("Source/target does not exist.");
    } catch (FileAlreadyExistsException e) {
      System.out.println(target + " already exists. Move failed.");
    } catch (DirectoryNotEmptyException e) {
      System.out.println(target + " is not empty. Move failed.");
    } catch (AtomicMoveNotSupportedException e) {
      System.out.println("Atomic move is not supported. MOve failed.");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Result