views:

157

answers:

4

hi. i would like to know which is the best way to copy large number of files.

+2  A: 

"Best" needs clarification.

I would delegate to rsync which is very good at copying a large number of files with a lot of options. I am not aware of a good Java implementation of rsync.

Thorbjørn Ravn Andersen
+1  A: 

Check out the Files class from Google's guava library. It contains some utility methods for copying whole files.

finnw
Only problem is that no released version of Guava exists yet - only option is to check out trunk sources from their svn. (Correct me if I'm wrong.)
Jonik
+2  A: 

As always, there is the Jakarta Commons : http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html

Guillaume
At the time of writing this, FileUtils.copyFile() uses IOUtils.copy(), which just reads from an InputStream and writes to an OutputStream. It doesn't do anything to detect the special case where you have a FileInputStream and a FileOutputStream and so could do a faster copy via channels. So, if the goal is to do the copy as fast as possible *and* the copy is local, then this won't be the fastest way.won't be the fastest way.
uckelman
+4  A: 

If you're copying files locally, you should use FileChannel.transferFrom() or FileChannel.transferTo(). For example:

FileInputStream is = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(oFile);
FileChannel f = is.getChannel();
FileChannel f2 = fos.getChannel();

f.transferTo(0, f.size(), f2);

f2.close();
f.close();

On many platforms, the copying will happen via DMA and be about as fast as possible.

If you're copying files over a network, then you're in a different situation. In the case that some of the files might already exist, then you should look into rsync, as it can avoid transferring parts of files which are the same on both sides. If the most common case is that the files won't already exist on the destination machine, then you'll want to use something like scp. For that, see this question.

uckelman
+1: Gotta love that DMA. But I'm afraid most kids don't know much about it. http://en.wikipedia.org/wiki/Direct_memory_access
Stu Thompson