Solved

copy whole directory in java

Posted on 2001-07-04
7
446 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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Application launch issue with Apache Tomcat 5 45
java stored proc example 9 32
Running JavaFX on JDeveloper 12C 1 32
sql import cannot be resolved jsp 3 23
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
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 about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
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:

809 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