Copying Directories

F

freesoft_2000

Hi everyone,

I am trying to copy directories from one place to
another in a
platform independent way. You see the directory i have contains some files
in it as well as other directories. Basically this directory also has
sub-directories.

Usually when i am copying an array of files this is what
i usually do

void copy(File[] src, File[] dst) throws IOException
{
i = 0;

for(i=0;i<src.length;i++)
{
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dst);

byte[] buf = new byte[1024];
int len = 0;

while ((len = in.read(buf)) > 0)
{
out.write(buf, 0, len);
}

in.close();
out.close();
}

}

The above code copies an array of files to the destination. The
thing now is that i need to copy an array of directories to a
destination. The thing with these directories is that contain
sub-directories and i am not able to copy the array of directories.

Basically my question is how do i copy directories that contain
files and sub-directories to a destination location?

Any help is greatly appreciated

Thank You

Yours Sincerely

Richard West
 
O

Oliver Wong

freesoft_2000 said:
The above code copies an array of files to the destination. The
thing now is that i need to copy an array of directories to a
destination. The thing with these directories is that contain
sub-directories and i am not able to copy the array of directories.

Basically my question is how do i copy directories that contain
files and sub-directories to a destination location?

I don't know how much Java you know, so it's hard to give a concrete
answer. Do you know about and understand recursion?

- Oliver
 
R

Roedy Green

The above code copies an array of files to the destination. The
thing now is that i need to copy an array of directories to a
destination. The thing with these directories is that contain
sub-directories and i am not able to copy the array of directories.

You collect an array of subdirs, then RECURCISIVELY process that list.


Here is a program for getting rid of junk files. It searches directory
trees for them.

Ignore the complications and look for the essential recursive logic.


package com.mindprod.batik;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;

/**
* Accept only Directories to be processed, reject files.
*/
class DirFilter implements FilenameFilter

{

/**
* Directories to be left untouched.
*/
private HashSet<String> mAvoidDirs;

/**
* Accept only directories to be processed.
*
* @param pDir
* the directory in which the dir/file was found.
* @param pName
* the name of the dir/file
* @return true if and only if the name should be included in the
list;
* false otherwise.
*/
public boolean accept ( File pDir, String pName )
{
try
{
File aFile = new File( pDir, pName );
if ( !aFile.isDirectory() ) return false;
String aDirname = aFile.getCanonicalPath().toLowerCase();
return !mAvoidDirs.contains( aDirname );
}
catch ( IOException e )
{
return false;
}
}

/**
* Defines which directories should be left untouched.
*
* @param pAvoidDirs
* Array of strings defining the fully qualified
directories to be
* left untouched.
*/

DirFilter( String[] pAvoidDirs )
{
// build HashSet containing list dirs to avoid.
// effectively just mAvoidDirs = new HashSet( Arrays.asList(
pAvoidDirs ) );
mAvoidDirs = new HashSet<String>( pAvoidDirs.length );

for ( int i = 0; i < pAvoidDirs.length; i++ )
{
String aDirname = pAvoidDirs[ i ];
try
{
File aFile = new File( aDirname );
aDirname = aFile.getCanonicalPath().toLowerCase();
if ( aFile.exists() )
{
System.out.println( "Avoiding directory " + aDirname
);
mAvoidDirs.add( aDirname );
}

}
catch ( IOException e )
{
throw new IllegalArgumentException( "invalid directory
name "
+ pAvoidDirs[ i ] );
}

}
}

} // end class DirFilter


/**
* accept only junk files
*/
class JunkFilter implements FilenameFilter {

/**
* Extension to be deleted, stored in lower case.
*/
private HashSet<String> mJunkExtensions;

/**
* filenames to be deleted, in lower case.
*/
private HashSet<String> mJunkFilenames;

/**
* Accept only junk files to be deleted.
*
* @param pDir
* the directory in which the file was found.
* @param pName
* the name of the file
* @return true if and only if the name should be included in the
file list;
* false otherwise.
*/
public boolean accept ( File pDir, String pName )
{
if ( pDir == null || pName == null ) return false;
if ( new File( pDir, pName ).isDirectory() ) return false;
String filename = pName;
String extension = "";
int whereDot = pName.lastIndexOf( '.' );

if ( 0 < whereDot && whereDot <= pName.length() - 2 )
{
extension = pName.substring( whereDot + 1 ).toLowerCase();
}
if ( 1 < whereDot )
{
filename = pName.substring( 0, whereDot ).toLowerCase();
}

// test extensions first as it is more likely to be true
return ( mJunkExtensions.contains( extension ) ||
mJunkFilenames
.contains( filename ) );
}

/**
* Defines which filenames and extensions are considered junk, to
be
* deleted.
*
* @param pJunkFilenames
* Array of strings defining the unqualified, extensionless
filenames
* considered junk.
* @param pJunkExtensions
* Array of strings defining unqualified, dotless filename
extensions
* considered junk.
*/
JunkFilter( String[] pJunkFilenames, String[] pJunkExtensions )
{
/* build HashSets containing lists of junk filenames and
extensions */
mJunkFilenames = new HashSet<String>( Arrays.asList(
pJunkFilenames ) );
mJunkExtensions = new HashSet<String>( Arrays.asList(
pJunkExtensions ) );
}
} // end class JunkFilter


/**
* <pre>
* Batik file deleter Batik is a skeleton program for writing
command line
* scripts, primarily to delete files. Unfortunately Java has no
support for
* file attributes. Java seems to treat hidden files as if they were
not hidden.
*
* @author copyright (c) 1999-2005 Roedy Green, Canadian Mind
Products Shareware
* that may be copied and used freely for any purpose but
military.
*
* Roedy Green Canadian Mind Products
* #327 - 964 Heywood Avenue
* Victoria, BC Canada
* V8V 2Y5 tel: (250) 361-9093
*
* mailto:[email protected]
* http://mindprod.com
*
*
* Futures: - fast file copy and xcopy
*
* copy to A: that checks sufficient space before doing all
the work.
*
* - design so that your script is an extension of the
Batik class, rather than built-in
* to it.
*
* - check status of spawned commands. - check status of
various
* file commands, invent an exception
*
* Version 1.0 1998 August 18
*
* Version 1.1 2001 March 1 : redo with FilenameFilter
logic
*
* Version 1.2 2001 March 13: clean up JavaDoc add support
for avoidDirs.
*
* Version 1.3 2002 March 11: add more dirs to clean, NT
-&gt; W2K
*
* Version 1.4 2005-06-17: stomp style bat files.
* </pre>
*/

public class Batik {

/**
* In debug mode, no files are actually deleted. Best to test your
changes
* in debug mode first.
*/
private static final boolean DEBUGGING = false;

// You might want to configure these constants:

/**
* exec command to invoke NT command processor customised for my
machine.
*/
private static String invokeCmd = "cmd /E:1900 /C ";

/**
* exec command to invoke Windows Command processor, customised
for my
* machine.
*/
private static String invokeCommand = "command /E:1900 /C ";

/**
* exec command to invoke 4DOS customised for my machine.
*/
private static String invokeForDOS = "C:\\4DOS\\4DOS601.COM
/E:1900 /C ";

/**
* exec command to invoke 4NT customised for my machine.
*/
private static String invokeForNT = "C:\\4NT401\\4NT.EXE /E:1900
/C ";

/**
* The shell I am using right now, namely 4NT.
*/
private static String invokeShell = invokeForNT;

/**
* FilenameFilter that accepts only directories to process.
*/
private static DirFilter mDirFilter = new DirFilter( new String[]
{} );

/**
* FilenameFilter that accepts only junk files to be deleted.
*/
private static JunkFilter mJunkFilter = new JunkFilter( new
String[] {},
new String[] {} );

/**
* Defines which directories should be left untouched. Stays in
effect until
* you redefine it.
*
* @param pAvoidDirs
* Array of strings defining the fully qualified
directories to be
* left untouched. Directory Strings must be lower case.
*/
public static void avoidDirs ( String[] pAvoidDirs )
{
mDirFilter = new DirFilter( pAvoidDirs );
}

// code from here on, you probably won't need to change.

/**
* CUSTOM Script to clean all my drives of junk, as defined by me.
You would
* modify this script section to suit your machine and recompile.
I repeat,
* you need to extensively modify this for your own use!!
*/
public static void cleanAllGeneva ()
{

// define directories I want left untouched. There is no point
is
// combing
// jdk for trash. There won't be any.
avoidDirs( new String[] {
"c:/windows/system32"
} );

try
{
// Do special clearing first, wiping various temp
directories of
// all files and subdirs.
// None of these methods will remove read-only or system
files,
// but they will remove hidden files.

System.out.println();
System.out.println( "Clearing temp and cache
directories..." );

// Some of these directories are hidden, but we can delete
contents
// anyway
deleteDirContents(
new File( "c:/program files/cast/bobby3.2/tmp" ), true
);
deleteDirContents(
new File(
"c:/program files/Common Files/Adobe/Picture CD
Catlogs/temp" ),
true );
deleteDirContents( new File( "c:/program
files/Gnotella/temp" ),
true );
deleteDirContents( new File( "c:/program files/juno/tmp"
), true );
deleteDirContents( new File(
"c:/program files/Music Match/Music Match/Jukebox
4/TEMP" ),
true );
deleteDirContents( new File(
"c:/program files/netscape/users/geni/cache" ), true
);
deleteDirContents( new File(
"c:/program files/Qualcomm/Eudora/plugins/Esp/Temp" ),
true );
deleteDirContents( new File(
"c:/program files/Real/RealJukebox/temp" ), true );
deleteDirContents( new File( "c:/temp" ), true );
deleteDirContents( new File( "c:/tmp" ), true );
deleteDirContents( new File( "c:/WINDOWS/TEMP" ), true );

}
catch ( Exception e )
{
java.awt.Toolkit.getDefaultToolkit().beep();
System.out.println( "Problem clearing temp directories."
);
System.out.println( e );
e.printStackTrace();
}
try
{
// clear junk extensions
System.out.println();
System.out.println( "clearing chkdsk remnants" );

// Wipe out files of form temp.* temp1.* and temp2.*,
// e.g. temp.txt temp1.dat temp2. but not template.txt.
// Wipe out files of form *.chk, *.s_dd
junk( new String[] {
"temp",
"temp1",
"temp2"
}, new String[] {
"chk",
"s_dd"
} );

System.out
.println( "clearing C drive of temp?.*, *.bak, *.tmp,
*.temp" );

junk( new String[] {
"temp",
"temp1",
"temp2"
}, new String[] {
"bak",
"tmp",
"temp"
} );

cleanDrives( new char[] {
'c'
} );

System.out.println();
}
catch ( Exception e )
{
java.awt.Toolkit.getDefaultToolkit().beep();
System.out.println( "Problem removing junk files from C:."
);
System.out.println( e );
e.printStackTrace();
}
try
{
// rebuild 4NT quick directory index
System.out.println();
System.out.println( "rebuilding 4DOS directory..." );
forDOS( "CDD /S" );
}
catch ( Exception e )
{
java.awt.Toolkit.getDefaultToolkit().beep();
System.out.println( "Problem rebuilding 4NT directory." );
System.out.println( e );
e.printStackTrace();
}

try
{
// clear recycle bins. Do last to rid stuff we just
deleted.
System.out.println();
System.out
.println( "clearing standard recycle bin, Norton
Protected Files must be cleared manually..." );
deleteDirContents( new File( "c:/Recycler" ), true );
}
catch ( Exception e )
{
java.awt.Toolkit.getDefaultToolkit().beep();
System.out.println( "Problem clearing recycle bins." );
System.out.println( e );
e.printStackTrace();
}

System.out.println();
System.out.println( "Done" );
} // end cleanAllGeneva

/**
* CUSTOM Script to clean all my drives of junk, as defined by me.
You would
* modify this script section to suit your machine and recompile.
I repeat,
* you need to extensively modify this for your own use!!
*/
public static void cleanAllRoedy ()
{
String user = "Administrator.ROEDY";

// define directories I want left untouched. There is no point
is
// combing
// jdk for trash. There won't be any.
avoidDirs( new String[] {
"e:\\program files\\java\\jdk1.5.0_04",
"c:\\winnt\\system32"
} );

try
{
// Do special clearing first, wiping various temp
directories of
// all files and subdirs.
// None of these methods will remove read-only or system
files,
// but they will remove hidden files.

System.out.println();
System.out.println( "Clearing temp and cache
directories..." );
File allUserDir = new File( "c:/Documents and Settings",
"all users.winnt" );
File cProgFiles = new File( "c:/Program Files" );
File eProgFiles = new File( "e:/Program Files" );
File userDir = new File( "c:/Documents and Settings", user
);
File appData = new File( userDir, "application data" );

// Some of these directories are hidden, but we can delete
contents
// anyway


// c:
deleteDirContents( new File( "c:/temp" ), true );
deleteDirContents( new File( "c:/tmp" ), true );
deleteDirContents( new File( "c:/vslick/backup" ), true );
deleteDirContents( new File( "c:/winnt/temp" ), true );
// c:
deleteDirContents( new File( "e:/dl/temp" ), true );
deleteDirContents( new File( "e:/temp" ), true );
deleteDirContents( new File( "e:/tmp" ), true );
deleteDirContents( new File( "e:/vslick/backup" ), true );
// alluser
deleteDirContents( new File( allUserDir,
"application data\textbridge\temp" ), true );

// c program files
deleteDirContents(
new File( cProgFiles, "Eudora/Plugins/Esp/temp" ),
true );
deleteDirContents( new File( cProgFiles,
"Labtec/WebCam/temp" ),
true );
deleteDirContents(
new File( cProgFiles,
"Logitech/desktop
messenger/8876480/users/administrator/misc/temp" ),
true );
// e program files
deleteDirContents( new File( eProgFiles, "agent/data/temp"
), true );
deleteDirContents( new File( eProgFiles, "decomp/temp" ),
true );
deleteDirContents( new File( eProgFiles,
"Opera8/cache4" ), true );
deleteDirContents( new File( eProgFiles, "Opera8/download"
), true );

deleteDirContents( new File( eProgFiles, "sr/temp" ), true
);
deleteDirContents( new File( eProgFiles,
"Trillian/users/default/cache" ), true );

// c appdata
deleteDirContents( new File( appData,
"mozilla/firefox/profiles/gt4rcgpi.default/cache" ),
true );
deleteDirContents( new File( appData,
"mozilla/profiles/default/96t8gg0w.slt/cache" ), true
);
deleteDirContents( new File( appData,
"mozilla/profiles/default/96t8gg0w.slt/cache" ), true
);
deleteDirContents( new File( appData,
"netscape/nsb/profiles/ienfrn46.default/cache" ), true
);
deleteDirContents( new File( appData,
"opera/Opera8/mail/cache" ),
true );
deleteDirContents(
new File( appData, "opera/Opera8/profile/cache4" ),
true );
deleteDirContents(
new File( appData, "real/realplayer/temp"), true );
deleteDirContents(
new File( appData, "sr/temp"), true );
deleteDirContents(
new File( appData, "sun/java/deployment/cache" ), true
);
deleteDirContents( new File( appData,
"sun/java/deployment/javaws/cache" ), true );

// userdir
deleteDirContents( new File( userDir, "Local
Settings/Temp" ), true );
deleteDirContents( new File( userDir,
"Local Settings/Temporary Internet Files" ), true );
deleteDirContents( new File( userDir, "My Documents" ),
false ); // unusual,
// not
// PadGen
deleteDirContents( new File( userDir, "recent" ), true );
}
catch ( Exception e )
{
java.awt.Toolkit.getDefaultToolkit().beep();
System.out.println( "Problem clearing temp directories."
);
System.out.println( e );
e.printStackTrace();
}
try
{
// clear junk extensions
System.out.println();

System.out.println( "clearing c:\\ab1\\util of remnants"
);
junk( new String[] {
"temp",
"temp1",
"temp2"
}, new String[] {
"csm",
"lst",
"map",
"obj"
} );
cleanDir( new File( "c:/ab1/util" ), true );

System.out
.println( "clearing all drives of temp?.*, *.bak,
*.tmp, *.temp" );
// name must be temp, not just begin temp e.g. template.
junk( new String[] {
"temp",
"temp1",
"temp2"
}, new String[] {
"bak",
"tmp",
"temp"
} );
cleanDrives( new char[] {
'c',
'e'
} );

System.out.println();
}
catch ( Exception e )
{
java.awt.Toolkit.getDefaultToolkit().beep();
System.out.println( "Problem removing junk files from C:
and E:." );
System.out.println( e );
e.printStackTrace();
}
try
{
// rebuild 4NT quick directory index
System.out.println();
System.out.println( "rebuilding 4NT directory..." );
forNT( "CDD /S CE" );
}
catch ( Exception e )
{
java.awt.Toolkit.getDefaultToolkit().beep();
System.out.println( "Problem rebuilding 4NT directory." );
System.out.println( e );
e.printStackTrace();
}

try
{
// clear recycle bins. Do last to rid stuff we just
deleted.
System.out.println();
System.out
.println( "clearing standard recycle bins, Norton
Protected Files must be cleared manually..." );
deleteDirContents( new File( "c:/Recycler" ), true );
deleteDirContents( new File( "e:/Recycler" ), true );

}
catch ( Exception e )
{
java.awt.Toolkit.getDefaultToolkit().beep();
System.out.println( "Problem clearing recycle bins." );
System.out.println( e );
e.printStackTrace();
}

System.out.println();
System.out.println( "Done" );
} // end cleanAllRoedy

/**
* Delete junk files in given fully qualified directory, and all
subdirs.
* uses currerent definition of junk. Wipes out files matching
definition of
* junk, not dirs.
*
* @param pDir
* fully qualified directory. Would normally be some
existing
* directory.
* @param pRecursive
* true if should also clean subdirs of this dir.
*/
public static void cleanDir ( File pDir, boolean pRecursive )
{
if ( pDir == null ) return;

// clean out child dirs
if ( pRecursive )
{
// all immediate child subdirs of this dir.
String[] allDirs = pDir.list( mDirFilter );
if ( allDirs != null )
{
for ( int i = 0; i < allDirs.length; i++ )
{
cleanDir( new File( pDir, allDirs[ i ] ), true );
}
}
}
// just junk files in this dir, not dirs themselves.
String[] allFiles = pDir.list( mJunkFilter );
if ( allFiles != null )
{
for ( int i = 0; i < allFiles.length; i++ )
{
deleteFile( new File( pDir, allFiles[ i ] ) );
}
}
}

/**
* get rid of junk files on given list of drives. Uses current
definition of
* junk and avoidDirs.
*
* @param pDrives
* array of chars giving drive letters to be procesesed,
not Strings,
* no colons. e.g. new char[]{'c','d'}
*/
public static void cleanDrives ( char[] pDrives )
{
// in JDK 1.2 could get list of drives, but we want list to be
cleaned,
// which is
// presumably a subset.
for ( int i = 0; i < pDrives.length; i++ )
{
System.out.println( " drive " + pDrives[ i ] );
cleanDir( new File( pDrives[ i ] + ":/" ), true );
} // end for
} // end cleanDrives

/**
* Submit command to NT command processor\ and wait for it to
complete.
*
* @param command
* @return Process spawned
* @see #shell
* @see #exec
* @see #command
* @see #cmd
* @see #forDOS
* @see #forNT
*/
public static Process cmd ( String command )
{
return exec( invokeCmd + command, true );
} // end cmd

/**
* Submit command to DOS command processor and wait for it to
complete.
*
* @param command *
* @return Process spawned
* @see #shell
* @see #exec
* @see #command
* @see #cmd
* @see #forDOS
* @see #forNT
*/
public static Process command ( String command )
{
return exec( invokeCommand + command, true );
} // end command

/**
* Get rid of ALL files and subdirectories in given directory, and
all
* subdirs under it, not just the junk names and extensions. The
directory
* itself is not deleted. Uses the current definition of junk and
avoidDirs.
*
* @param pDir
* would normally be an existing directory.
* @param pRecursive
* true if want subdirs deleted as well
*/
public static void deleteDirContents ( File pDir, boolean
pRecursive )
{
if ( pDir == null )
{
System.err.println( " no such directory" );
return;
}

// We must empty child subdirs contents before can get rid of
immediate
// child subdirs
if ( pRecursive )
{
String[] allDirs = pDir.list();
if ( allDirs != null )
{

for ( int i = 0; i < allDirs.length; i++ )
{
deleteDirContents( new File( pDir, allDirs[ i ] ),
true );
}

}
}
// delete all files and subdirs in this dir
String[] allFiles = pDir.list();
if ( allFiles != null )
{
for ( int i = 0; i < allFiles.length; i++ )
{
deleteFile( new File( pDir, allFiles[ i ] ) );
}

}
} // end deleteDirContents

/**
* get rid of this fully qualified file. Display message on
console about
* success.
*
* @param pFile
* fully qualified file that we want to delete.
*/
public static void deleteFile ( File pFile )
{
String aFilename = pFile.getAbsolutePath();
boolean success;
if ( DEBUGGING )
{
success = true;
}
else
{
success = pFile.delete();
}
if ( success )
{
System.out.println( " => " + aFilename );
}
else
{
System.out.println( " ?? " + aFilename );
}
} // end deleteFile

/**
* Display the fully qualified name of the given directory/file.
*
* @param pFile
* The file or directory to be displayed.
*/
public static void displayTrueName ( File pFile )
{
try
{
System.out.println( pFile.getCanonicalPath() );
}
catch ( IOException e )
{
System.out.println( e );
}
} // end displayTrueName

/**
* wrapper for Runtime.exec. You will not see the console output
of the
* spawned command.
*
* @param pCommand
* fully qualified *.exe or *.com command
* @param pWait
* true if you want to wait for this spawned task to
complete. false
* if you want it to run in parallel.
* @return Process object to control the spawned execution.
* @see #shell
* @see #exec
* @see #command
* @see #cmd
* @see #forDOS
* @see #forNT
*/
public static Process exec ( String pCommand, boolean pWait )
{
Process p;
try
{
p = Runtime.getRuntime().exec( pCommand );
}
catch ( IOException e )
{
return null;
}

if ( pWait )
{
try
{
p.waitFor();
}
catch ( InterruptedException e )
{

}
} // end if
return p;
} // end exec

/**
* Submit command to 4DOS command processor and wait for it to
complete.
*
* @param command
* shell command to execute
* @return Process spawned
* @see #shell
* @see #exec
* @see #command
* @see #cmd
* @see #forDOS
* @see #forNT
*/
public static Process forDOS ( String command )
{
return exec( invokeForDOS + command, true );
} // end forDOS

/**
* Submit command to 4NT command processor
*
* @param command
* shell command to execute
* @return Process spawned
* @see #shell
* @see #exec
* @see #command
* @see #cmd
* @see #forDOS
* @see #forNT
*/
public static Process forNT ( String command )
{
return exec( invokeForNT + command, true );
} // end forNT

/**
* Defines which filenames and extensions are considered junk, to
be
* deleted. Stays in effect until you redefine it.
*
* @param pJunkFilenames
* Array of strings defining the unqualified, extensionless
filenames
* considered junk. i.e. name.* files will be deleted.
Strings should
* be lower case. name*.* will NOT be deleted.
* @param pJunkExtensions
* Array of strings defining unqualified, dotless filename
extensions
* considered junk. i.e. *.ext files will be deleted.
Strings should
* be lower case.
*/
public static void junk ( String[] pJunkFilenames, String[]
pJunkExtensions )
{
mJunkFilter = new JunkFilter( pJunkFilenames, pJunkExtensions
);
}

/**
* Standard main, cleans all drives of junk files.
*
* @param args
* not used
*/
public static void main ( String args[] )
{
cleanAllRoedy();
System.exit( 0 );
} // end main

/**
* Submit command to default shell command processor, and wait for
it to
* complete.
*
* @param command
* shell command to execute
* @return Process spawned
* @see #shell
* @see #exec
* @see #command
* @see #cmd
* @see #forDOS
* @see #forNT
*/
public static Process shell ( String command )
{
return exec( invokeShell + command, true );
} // end shell

} // end class Batik
 
R

Roedy Green

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,481
Members
44,900
Latest member
Nell636132

Latest Threads

Top