Move Files One Directory Another Directory Java

Move Files One Directory Another Directory Java

In this sample program you will see how to move files from one directory to another directory. We will use three different way to move file using below:

  • java.io.File (JDK 6)
  • java.nio (JDK 7)
  • Using Apache Commons

Sample java program:

package com.javahonk;

import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.commons.io.FileUtils;

public class MoveFilesOneDirectoryToAnother {

	public static void main(String[] args) throws IOException {
		
		//Example 1 using JDK 6
		File sourceFile = new File("C:\\JavaHonk\\zip\\SpringMVCRESTFulService\\pom.xml");
		String destinationDirectory = "C:\\JavaHonk\\zip\\pom.xml";
		
		boolean isMoved = sourceFile.renameTo(new File(destinationDirectory));
	    if (isMoved) {
	        System.out.println("Example 1 File moved successfully to : "+"C:\\JavaHonk\\zip");
	    }
	    
	    //Example 2 using JDK 7
	    
	    Path sourceFilePath = Paths.get("C:\\JavaHonk\\zip\\SpringMVCRESTFulService\\pom2.xml");
	    Path destinationDirectoryPath = Paths.get("C:\\JavaHonk\\zip\\pom2.xml");
	 
	    Files.move(sourceFilePath, destinationDirectoryPath, REPLACE_EXISTING);	
	    System.out.println("Example 2 File moved successfully to : "+destinationDirectoryPath.getParent());
	    
	    //Example 3 using Apache Commons IO (Preferred approach)
	    FileUtils.moveFileToDirectory(
	    FileUtils.getFile("C:\\JavaHonk\\zip\\SpringMVCRESTFulService\\pom3.xml"), 
	    FileUtils.getFile("C:\\JavaHonk\\zip\\"), true);
	    System.out.println("Example 3 File moved successfully to : "+"C:\\JavaHonk\\zip");


	}

}
  • Output:

Move Files One Directory Another Directory Java

For more information about files please refer oracle documentation here

Leave a Reply

Your email address will not be published. Required fields are marked *