Is it possible to change directory by using File object in Java?


The File class

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

This class provides various methods to manipulate files, The renameTo() 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 source path to the destination path.

Example

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 . . . . . . .

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 . . . . . . .

Updated on: 01-Aug-2019

978 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements