How to move files using FileUtils in Java?


Using the File class

The class named File of the java.io package represents a file or directory (pathnames) in the system. This class provides various methods to perform various operations on files/directories.

This class provides various methods to manipulate files, The rename() method of the File class accepts a String representing a destination file and, renames the abstract file path of the current file to the given one.

This method actually moves the file from the source path to the destination path.

Example

 Live Demo

import java.io.File;
public class MovingFile {
   public static void main(String args[]) {
      //Creating a source file object
      File source = new File("D:\\source\\sample.txt");
      //Creating a destination file object
      File dest = new File("E:\\dest\\sample.txt");
      //Renaming the file
      boolean bool = source.renameTo(dest);
      if(bool) {
         System.out.println("File moved successfully ........");
      }
      else {
         System.out.println("Unable to move the file ........");
      }
   }
}

Output

File moved successfully . . . . . . .

Using the Files class

Since Java 7 the Files class was introduced this contains (static) methods that operate on files, directories, or other types of files.

The move method of this class accepts two path objects source and destination (and a variable argument to specify the move options) respectively and moves the file represented by the source path to the destination path.

Example

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class MovingFile {
   public static void main(String args[]) throws Exception {
      //Creating a source Path object
      Path source = Paths.get("D:\\source\\sample.txt");
      //Creating a destination Path object
      Path dest = Paths.get("E:\\dest\\sample.txt");
      //copying the file
      Files.move(source, dest);
      System.out.println("File moved successfully ........");
   }
}

Output

File moved successfully . . . . . . .
raja
Published on 11-Sep-2019 17:37:37
Advertisements