Solved

copy whole directory in java

Posted on 2001-07-04
7
457 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
Transaction Monitoring Vs. Real User Monitoring

Synthetic Transaction Monitoring Vs. Real User Monitoring: When To Use Each Approach? In this article, we will discuss two major monitoring approaches: Synthetic Transaction and Real User Monitoring.

 
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
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…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

728 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