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
 
 
Search All Tutorials

 
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
 
Java
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

Moving file or directory from one directory to another

                         

Introduction

In this section, you will learn how  the contents of a file or a complete directory is moved from one directory to another directory. This program illustrates you the method or procedure for moving a file or directory contents from one directory to another. In this section an example is given for the best illustration of the procedure through which you can easily move contents of the mention file or directory as a source directory to the destination directory. If the mentioned source file or directory does not exist then the following program gives you a message "File or directory does not exist." then the control quits from the program. If the mentioned destination directory does not exist then the program asks you for the creation of the directory with the given name and if you enter "y", it will create a new directory and copy all the files and folders contained in the source directory. This program also asks for the replace folder or file if the mentioned destination file or directory already exists.

For running the program properly you must have to mention the complete path for the source or the destination from/to the files or the folders have to be moved. In the following program there are three methods have been used excepting the main method to complete the program for moving file or complete folder from specified source if exists to destination. These methods are explained one-by-one in brief as follows:

copyDirectory(File sourceDir, File destDir):
This the user define method which is used for the copying directory or folders where it found. This method passes two arguments in which one is the source directory name and another is the destination directory name. Both directory name must must be in the File type format.

copyFile(File source, File dest):
This is also a user defined method i.e. used for copying files from the source directory to the destination directory. This method passes two types of arguments in which one is the source file name and another is the destination file name and both file name must has to be mentioned in the File type format.

delete(File resource):
This is the method which has created in the following program for deleting all the files or the folders that have to be moved from the source to destination. This method starts deletion of files and folders after copying these to the destination directory. This method passes the resource file name which has to be deleted after moving.

import java.io.*;

  import javax.swing.*;
 


public class MovingFile{
 
  
public static void main(String[] args) throws IOException{
 
    
int a = 0;
 
   
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter the file or directory name that has to be moved : ");
 
   
String src = in.readLine();
 
    
if(src.equals("")){
 
     
System.out.println("Invalid directory or file name.");
 
      
System.exit(0);
 
   
}
 
   
File source = new File(src);
 
    
if(!source.exists()){
 
     
System.out.println("File or directory does not exist.");
 
      
System.exit(0);
 
   
}
    
System.out.print("Enter the complete path where file or directory 
                       has to be moved: "
);
 
    
String dest = in.readLine();
 
    
if(dest.equals("")){
 
      
System.out.println("Invalid directory or file name.");

        System.exit(0);
 
   
}
  
  
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 = in.readLine();
 

      
if(chk.equals("Y") || chk.equals("y")){
 
       
destination.mkdir();
   
     
copyDirectory(source, destination);
 
       
a = 1;
  
    
}
  
    
else if(chk.equals("N") || chk.equals("n")){
 
       
System.exit(0);
  
    
}
     
 
else{
  
      
System.out.println("Invalid Entry!");
 
       
System.exit(0);
  
    
}
    
}
    
else{
 
      
int num = JOptionPane.showConfirmDialog(null,                            "Given file or folder name already exists. \nDo you want to replace now?");
 
     
if(num == 0){
 
        
copyDirectory(source, destination);
  
      
a = 1;
    
  
}
   
 
}
  
  
if(a == 1){
 
      
System.out.println("File or directory moved successfully.");
 
     
if(!delete(source)){
 
       
throw new IOException("Unable to delete original folder");
 
     
}
 
   
}
    else if(a == 0){
  
    
System.exit(0);
   
 
}
 
 
}

 
  
public static void 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()){
 
       
copyDirectory(sourceChild, destChild);
 
      
}
     
 
else{
  
      
copyFile(sourceChild, destChild);
 
     
}
   
 
}
 
 
}
 
 

  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();
 
        
}
 
  
}

 
 
public static boolean delete(File resource) throws IOException{ 

      if(resource.isDirectory()){
 
      
File[] childFiles = resource.listFiles();
 
      
for(File child : childFiles){
  
      
delete(child);
   
   
}
   
 
}
    
return resource.delete();
 
  
}
 
}


Here is the code of the program : 

Output: Here "test" is the root folder and "source" directory already exist in this folder. If you want to move "source" into "destination". Please run program this way...


C:\work\chandan>javac MovingFile.java

C:\work\chandan>java MovingFile
Enter the file or directory name that has to be moved : E:\source
Enter the complete path where file or directory has to moved: c:\work\chandan\destination
Mentioned directory does not exist.
Do you want to create a new directory(Y/N)? y
File or directory moved successfully.

C:\work\chandan>

If you want to move file or directory from other directory .Please enter qualified path of  "source" and destination and run this program this way... 

Download this example

                         

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

Current Comments

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

i m not getting the meaning of statement:-
for(File child : childFiles)
As i m using java1.4.2_06 and getting error in the program given by you.
Please help out.

Posted by naveen verma on Friday, 03.7.08 @ 17:19pm | #51842

I use the line destDir.mkdirs() instead of destDir.mkdir() in the function copyDirectory(File sourceDir, File destDir), and it works
It was very helpfull

Posted by mounstrigirl on Saturday, 02.23.08 @ 23:41pm | #49691

Moving File code has been very usefull. I had been looking around the whole week for something like that. I am doing java at college. Thanks for this code. Could you be contacted in future for some java help?
Deo
Wisconsin, USA.

Posted by Deo on Thursday, 02.7.08 @ 11:51am | #47490

I tried using the same way to move files in java but the behavior is very inconsistent - it copies successfully but sometimes deletes and sometimes not.

Please see if you can suggest some other solution for file movement

Posted by Jyoti on Thursday, 01.25.07 @ 19:46pm | #4364

I don't think it is in business,in fact it can not work well when I tried to move a folder to another dirctory

Posted by flyhaotian on Tuesday, 12.12.06 @ 12:59pm | #883

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

 

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.

Hot Web Programming Job

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

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

Copyright © 2007. All rights reserved.