Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML


 
  
 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 

 
Facing Programming Problem?
Ask Questions?, Browse Latest Questions, Question-Answer Guidelines
Java
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

Copy Directory in Java

                         

Introduction

Java has the features of the copying the directory and it's contents. This example shows how to copy the directory and files into a new directory.

In this program, you will see how contains of a directory or a file is copied  from the specified source directory (subdirectories and files) to specified destination directory. If you specify the unknown source directory which does not exist then the program gives the output message like : File or directory does not exist. otherwise read the source directory name and create the OutputStream instance for the destination directory while if you specify the unknown destination directory name then the program creates new directory with that name for the destination directory where the contents of the source directory have to be copied.

In this program, there are two methods have been used to complete the program. These methods are explained ahead : 

copyDirectory (File srcPath, File dstPath):

The copyDirectory() method is used to copy contents from the specified source directory to the specified destination directory. This method takes two File type arguments passed by the calling method in the main method and check whether the specified directory is a directory exactly or not. If the specified name is in the exact directory format and that exists then the method generates the list of all the sub directories and file inside the source directory using the list() method and copy one by one to the destination directory otherwise the specified name is copies (treated) as a file name directly.

And another method is the main method in which the program read the source and destination directory or file name.

Here is the code of the program : 

import java.io.*;

  public class CopyDirectory{
 
 
public static void main(String[] argsthrows IOException{
 
   
CopyDirectory cd = new CopyDirectory();
    BufferedReader in = new BufferedReader
                        (
new InputStreamReader(System.in));
    System.out.println("Enter the source directory or file name : ");

      String source = in.readLine();

    File src = new File(source);
 
    
System.out.println("Enter the destination 
                 directory or file name : "
);
    String destination = in.readLine();
  
      
File dst = new File(destination)

    cd.copyDirectory(src, dst);

  }
  

  public void copyDirectory(File srcPath, File dstPath)
                               
throws IOException{
  
  
if (srcPath.isDirectory()){

      if (!dstPath.exists()){

        dstPath.mkdir();
 
     
}

 
     
String files[] = srcPath.list();
  
    
for(int i = 0; i < files.length; i++){
        copyDirectory(new File(srcPath, files[i])
                    
new File(dstPath, files[i]));
 
      
}

    }
 
   
else{
 
      
if(!srcPath.exists()){

        System.out.println("File or directory does not exist.");
 
       
System.exit(0);

      }
      
else

 
      
{
 
       
InputStream in = new FileInputStream(srcPath);
       OutputStream out = new FileOutputStream(dstPath); 
                    
// Transfer bytes from in to out
            byte[] buf = new byte[1024];
 
              
int len;
 
           
while ((len = in.read(buf)) 0) {
 
          
out.write(buf, 0, len);

        }
 
       
in.close();
 
           
out.close();

      }
 
   
}
   
 
System.out.println("Directory copied.");
 
 
}

}


Output of the Program:

C:\nisha>java CopyDirectory
Enter the source directory or file name :test
Enter the destination directory or file name :dir1
Directory copied.

Download this example.

                         

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

10 comments so far (
post your own) View All Comments Latest 10 Comments:

Program is amazing. Saved my time.

Posted by Anil on Friday, 09.19.08 @ 18:28pm | #80545

i want to copy MS Access file ie database file can this program works? if not then what can be the possible solution.

Posted by Virendra on Wednesday, 02.20.08 @ 09:34am | #49170

I love your code. It was just right for my purpose.
Deo
Wisconsin, USA.

Posted by Deo on Thursday, 02.7.08 @ 22:22pm | #47537

i downloaded the code and it worked.thanx

Posted by ismol_but_teribol on Saturday, 01.5.08 @ 09:27am | #44550

i downloaded the source code and it worked.

Posted by ismol_but_teribol on Saturday, 01.5.08 @ 09:23am | #44549

i want to get the absolute path of the file , when i give the drive name and file name dynamically,and it shulod be opend with saparete
window

Posted by sandeep T on Saturday, 05.5.07 @ 00:20am | #15283

i want to get the absolute path of the file , when i give the drive name and file name dynamically,and it shulod be opend with saparete
window

Posted by sandeep T on Saturday, 05.5.07 @ 00:19am | #15282

WHEN I USED THIS PROGRAM, IT COPIED SUCCESSFULLY BUT WHEN I LOOKED TO THE SIZE OF THE FILES IT IS SHOWING ME THE 1KB.THOGH THE ORIGINAL FILE SIZE IS MORE THAN 1KB.

Posted by HRUSHIKESH on Thursday, 03.15.07 @ 18:35pm | #11814

What is the error?

Posted by Deepak on Tuesday, 12.5.06 @ 12:30pm | #407

When i compile this program it gives me a lot of error??

Posted by Pawandeep Toor on Monday, 12.4.06 @ 22:37pm | #395

Latest Searches:
awt example
what is static inner c
printing from jsf-page
how to run ruby applic
java programm for arra
jfreechart
JSP:File Browse
animation programme in
Getproperty
canonical path
<html:submit>
Passing Parameters in
Write a program that d
difference between inc
Copy One Database Tabl
ASPAdManagementRotatin
string functions in ja
UPDATE QUERY JAVA
ad
onloading the page ret
PHP Date and time func
jcreator code of calcu
XMLBeans
assign flex label text
removing spaces betwee
convert unicode charac
goto
goto line
ASP EXAMPLE and char(1
include a file in dire
open close session
struts custom tag
insert data to html fi
resultsetmethods
how to split string c
break?ΠΆΠ????????ΠΆΠ??
asterisk
jQuery To Hide the Div
stored procedure in hi
how to reference index
session bean
Java EJB EJB exception
div
syntax
Contenttype
client/server
struts validation fram
HSSF clone cell
j2me insert image usin
insert loop
command Sort Header on
Quartz
java program to transp
redirecting
jsp
out in jsp
difference between arr
sample
java ????ΆΡ????? ?????
javaclient/serverprogr
static
actionperformed
insert data tohtml fil
clipiing source code i
html to pdf
GetCharFromString usin
how to write in pdf us
j2me datefield
errors
clear values from a fo
write a xml file using
struts supported jar f
session.set attribute(
append message
types of heap sort
sort object compareTo
call javascript throug
File
using the selection so
DefaultMutableTreeNode
Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.