Tuesday, 10 May 2011

Moving file or directory from one directory to another

Here we write function to copy file or directory from one place to other.

public static boolean moveFileOrDirectory(String src, String dst){
File source = new File(src);
if(!source.exists())
return false;


File destination = new File(dest);
if(!destination.exists()){
System.out.print("Mentioned directory does not exist.
\nDo you want to create a new directory(Y/N)? "
);

String chk = readString();
if(chk.equals("Y") || chk.equals("y")){
destination.mkdir();
return copyDirectory(source, destination);
}else{
return false;
}
}else //if file or directory already exists, we have to copy and
//overwrite the already existing one
{
System.out.println("Given file or folder name already exists.
\nDo you want to replace now?"
);
String chk = readString();
if("Y".equals(chk) )
return copyDirectory(source, destination);
else return false;
}
}



 


Now this function makes use of copyDirectory function which can be written like this:



public static boolean copyDirectory(File sourceDir, File destDir) throws
IOException{

if(!destDir.exists()){
destDir.mkdir();
}

File[] children = sourceDir.listFiles();
for(File sourceChild : children){

String name = sourceChild.getName();

File destChild = new File(destDir, name);

if(sourceChild.isDirectory()){

return copyDirectory(sourceChild, destChild);

}

else{

return copyFile(sourceChild, destChild);

}

}

}



Now this in turn makes use of copyFile function.



public static void copyFile(File source, File dest) throws IOException{

if(!dest.exists()){

dest.createNewFile();

}

InputStream in = null;

OutputStream out = null;

try{

in = new FileInputStream(source);

out = new FileOutputStream(dest);

byte[] buf = new byte[1024];

int len;

while((len = in.read(buf)) > 0){

out.write(buf, 0, len);

}

}

finally{

in.close();

out.close();

}
return true;

}

No comments:

Post a Comment