Solved

copy whole directory in java

Posted on 2001-07-04
7
440 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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
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…

762 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

22 Experts available now in Live!

Get 1:1 Help Now