How to move file to another directory in Java?

Here is a some Example to explain how to move file to another directory in Java

  • First Example with renameTo
package com.nourit.javaIO;

import java.io.File;

public class MoveFileExample1 {

  public static void main(String[] args) {
    File source =new File("D:/tmp/nourit.txt");

    if(source.renameTo(new File("D:/tmp/nourit/" + source.getName()))){
      System.out.println("Succesful Move");
    }else{
      System.out.println("Move failed");
    }
  }
}
  • Second Example with copy and delete method
package com.nourit.javaIO;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class MoveFileExample1 {

  public static void main(String[] args) {
    try {
      File source = new File("D:/tmp/nourit.txt");// from Folder tmp
      File dest = new File("D:/tmp/nourit/nourit.txt");//To Folder nourit
      FileUtils.copyFile(source, dest);
      source.delete();
      System.out.println("Move succesful!");
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

 

Output:

Succesful Move

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*