views:

315

answers:

4

What is a better option (in terms of performance): copying a file using fileinputstream and fileoutputstream or running a OS specific command copy command from Java?

+2  A: 

I'm quite sure using the OS specific copy command would be faster or at least as fast as a simple self-written solution. The OS specific command probably uses a sensible buffer size and other optimizations which you would otherwise have to figure out yourself.

Edit:
x-x is right, you should not call the copy command directly. I thought Java already had a copy method, like File.copy() or something, but I couldn't find anything, not even in JDIC. So Apache Commons IO is probably the way to go.

mooware
+2  A: 

Use the excelent commons-io library, it has a method that will do exactly that. It is very widely used and rest assured it is very optimized.

Download it from here, or copy the POM dependency into your pom.xml file if using maven.

Don't copy with OS specific copy, it will not be portable. Using non-java code from java, whether with JNI or spawning an external command is a headache and maintenance nightmare.

flybywire
assuming portability is not the primary concern here, the primary use case of such a method will involve copying many files as part of the request processing and thus performance being a very imp criterion.
jjoshi
even if performance is an important criterion, the bottleneck will be disk and not cpu so it does not matter in what language you do it.
flybywire
A library to do a file copy!!! That's going a bit overboard for about 5 lines of code isn't it? Or does it use some arcane Java concurrent read/write calls for maximum throughput?
Adrian Pronk
@Adrian, the bottleneck is disk speed. Files cannot be copied faster than the speed of disk, and if you it reasonably, they can't be copied slower either.
flybywire
@x-x: I always prefer to use very large copy-buffers (~16Mb) if I feel it's safe to use so much RAM to avoid the possibility of disk seek thrashing in case the OS decides to interleave the reads and writes too much. Also, I've seen file-copies that use 1-byte buffers and they are often noticeably slow.
Adrian Pronk
+1  A: 

Do it in Java.

One problem with running an OS command is that you have to create a full process at the OS kernel level and that's a heavyweight operation. There is a large fixed overhead which will be particularly serious for smaller files.

The other problem is that it adds a system dependency without a good reason.

DigitalRoss
+1  A: 

Depends on what you will do in case of errors. Often the native command is better capable of handling error situations, but you may have a hard time making it interact with the user.

A pure java solution (besides being cross platform) allows you to be fully in control - I would suggest using a library to handle the messy details and error situations.

Thorbjørn Ravn Andersen