Solved

copy whole directory in java

Posted on 2001-07-04
7
460 Views
Last Modified: 2011-09-27
Hi all,
   I need to copy the whole directory(including all files inside the directory) to another directory using java. Can anyone help me on this?
   The server I'm using is NT.
   Thanks.
0
Comment
Question by:mkngau
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
7 Comments
 
LVL 92

Expert Comment

by:objects
ID: 6252087
Java's not real good at that. You have to actually open every file, read it and write it to the copy file.

If you don't need a x-platform solution it's probably a lot easier to use exec() to call the relevant DOS command to do the copy.
0
 

Author Comment

by:mkngau
ID: 6252150
Hi objects,
   How are you? Thanks for your previous help.
   regarding your recommendation :

"If you don't need a x-platform solution it's probably a lot easier to use exec() to call the relevant
DOS command to do the copy."

   Can you explain in detail how can I use exec()? Is it call from my java code?
   Thanks.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 6252261
Something like:

    Process proc = Runtime.getRuntime().exec( "DIR" ) ;
    BufferedInputStream is = new BufferedInputStream( proc.getInputStream() ) ;
    byte[] buf = new byte[ 4096 ] ;
    int cnt = 0 ;
    String out = "" ;
    while( ( cnt = is.read( buf, 0, 4096 ) ) != -1 )
    {
      out += new String( buf, 0, cnt ) ;
    }

then the String "out" will be a directory listing...

Good luck,

Tim.
0
Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

 
LVL 4

Expert Comment

by:omry_y
ID: 6253101
why not use
new File("c:\\directory").list();

I think java is the way to go.
my experience shows me, that using exec is something one need to avoid, because in most cases, it make the program not just platform dependent, but also COMPUTER dependent.
(ie - working on just one computer).
0
 
LVL 4

Accepted Solution

by:
omry_y earned 100 total points
ID: 6253133
using the following source, you can copy files with this line :

FileUtils.traverseDir(new File("c:\\source_dir\\"),new GenericFileFilter("*.*"),new FileCopy(new File("c:\\source_dir\\"),new File("c:\\dest_dir\\")));


I hope I didn`t miss anything, but basicly, you have enough here to get going.
if you have any questions, just ask.


**FILE Visitor.java**

public interface Visitor
{
    public void visit(Object arg);
}



**FILE FileUtils.java**

public class FileUtils
{
    public static void traverseDir(File f,FileFilter filter,Visitor visitor)
    {
        if(f.isDirectory())
        {
            File files[] = f.listFiles(filter);
            for (int i = 0; i < files.length; i++)
            {
                traverseDir(files[i],filter,visitor);
            }
        }else
        {
            visitor.visit(f);
        }
    }
}




**FILE FileCopy.java**


import java.io.*;

/**
 * $Id$
 * $Log$
 * Copyright:  Copyright (c) 2001
 * Company:    Telmap
 * @author
 * @version 1.0
 */

public class FileCopy implements Visitor
{
    // copying files from here.
    private File sourceDir;
    // copying files to here.
    private File destDir;

    public FileCopy(File sourceDir,File destDir)
    {
        this.sourceDir = sourceDir;
        this.destDir = destDir;
    }

    public void visit(Object arg)
    {
        File sourceFile = (File)arg;
        String relativeSourceFile = sourceFile.toString().substring(sourceDir.toString().length()+1);
        try
        {
            copyFile(new File(sourceDir,relativeSourceFile),new File(destDir,relativeSourceFile));
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }


    public static void copyFile(File src, File dest) throws IOException
    {
        FileInputStream in = null;
        FileOutputStream out = null;
        try
        {
            if(dest.isDirectory())
            {
                dest.mkdirs();
            }else
            {
                new File(dest.getParent()).mkdirs();
            }
            in = new FileInputStream(src);
            out = new FileOutputStream(dest);

            ByteArrayOutputStream outBuf = new ByteArrayOutputStream((int)src.length());

            byte[] buffer = new byte[4096];
            int count = in.read(buffer);
            while (count > 0)
            {
                outBuf.write(buffer, 0, count);
                count = in.read(buffer);
            }
            out.write(outBuf.toByteArray());
        }
        finally
        {
            try
            {
                if(in != null) in.close();
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
            try
            {
                if(out != null) out.close();
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
            }
        }
    }

}




**FILE GenericFileFilter.java**

import java.io.*;


/**
 * A file filter that recognize *.*, *.ext (any file with the given extendsion), and name.* (any file with the given name)
 */
public class GenericFileFilter implements FileFilter
{
    private String pattern;
    private boolean includeDirs;

    public GenericFileFilter(String pattern)
    {
        this(pattern,true);
    }

    public GenericFileFilter(String pattern, boolean includeDirs)
    {
        this.pattern = pattern;
        this.includeDirs = includeDirs;
    }

    public boolean accept(File pathname)
    {
        if(pathname.isDirectory()) return includeDirs;

        String name = pathname.getName();
        if(pattern.equals("*.*"))
        {
            return true;
        }else
        if(pattern.startsWith("*."))
        {
            String patternExt = pattern.substring(pattern.indexOf(".")+1);
            return name.endsWith("."+patternExt);
        }else
        if(pattern.endsWith(".*"))
        {
            String patternName = pattern.substring(0,pattern.indexOf("."));
            return name.startsWith(patternName+".");
        }else
        {
            return false;
        }
    }
}


0
 
LVL 92

Expert Comment

by:objects
ID: 6254171
// Execute native command
Process proc = Runtime.getRuntime().exec("xxxx");
// Wait for command to finish
p.waitFor();

where xxxx is replaced by the DOS command to do the delete.


0
 

Expert Comment

by:AttilaB
ID: 36712409
omry_y:

I will still need to go through to fully understand this, but this code just simply WORKS.
I only had to add a missing import for it, importing java.io.FileFilter for class header FileUtils.
Then, I was copying a folder over a network connection and it just worked fine.

Great code, thanks.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses

623 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question