Solved

copy whole directory in java

Posted on 2001-07-04
7
442 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
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
topping3 challenge 14 69
JDeveloper 12c for 32 bit 4 68
Java array passed to SQL where clause 23 62
Error trying to install RTMT Win7 5 40
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

914 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now