Tuesday, July 2, 2013

Move Files

With FileMover program, you can easily move your files from a source directory to another destination directory on your computer. You can choose to move all files or move only files that have a specific extension.
The program allows you to input source directory, file extension, destination directory, and override confirmation. If you want to move all files, input *. for the file extension. You can choose to override the existing files or not to override the existing files by inputting yes or no for the override confirmation.

move files in java

FileMover source code:

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

public class  FileMover{

public static void main(String args[]) throws IOException{



}catch(ArrayIndexOutOfBoundsException aiobe){System.out.println("Invalid input parameters");}


public static void moveFiles(String fromDir,String ext,String toDir, String override){
//create file object to encapsulate the source directory
File from_dir=new File(fromDir);
//make the sure the source directory exists
System.out.println("Source directory does not exist.");

//create file object to encapsulate the destination directory
File to_dir=new File(toDir);
//check the existence of the destination directory
//if does not exist, create it
boolean suc=to_dir.mkdirs();
if(!suc) {
System.out.println("Can't create the directory.");
//make sure the destination directory is writable
else if(!to_dir.canWrite()){
System.out.println("Destination folder is not writable. Please input another folder.");
String[] files;
if(!ext.equals("*.")) //select files with the specified extension
files=from_dir.list(new Filter(ext));
else //select all files

//Move files from input source directory to destination directory
for(String f:files){
File source=new File(from_dir+"/"+f);
File dest=new File(to_dir+"/"+f);
if(dest.exists() && override.equals("yes"))


class Filter implements FilenameFilter{
String ext="";
public Filter(String ext){
public boolean accept(File f, String name){
if(name.endsWith(ext)) return true;
else return false;


In the code below, firstly we need to check whether the source directory exists or not. Moving files can not continue if the source directory does not exist. We also check the existence of the destination directory. If it does not exist, it will be created. After that the files in the source directory are listed. These can be all files int he directory or files that have a specified extension. The rename method of the File class is used to move files from the source to destination directory. If the override confirmation is yes, the existing files in the destination directories are deleted before moving the files to that directory.

No comments:

Post a Comment