Revision v2
Per feedback:
- Close streams in finally block
- Source and destination parameters are now of type File instead of String
- Function is void, and throws IOException if error
—-
Quick snippets are posted live, this little ditty was written all of ten minutes ago. I needed a quick function to copy one file to another location in a small Java project I have going. Java does have a File.renameTo function that can be used to move a file, so to copy we have to actually read and write the file to the new location. This quick snippet can be included and used globally, in addition the buffer size can be changed for better performance.
[java]
// Copy file
public static void copyFile(File fSource, File fDest) throws IOException
{
// Declare variables
InputStream sIn = null;
OutputStream sOut = null;
try
{
// Declare variables
int nLen = 0;
sIn = new FileInputStream(fSource);
sOut = new FileOutputStream(fDest);
// Transfer bytes from in to out
byte[] bBuffer = new byte[1024];
while ((nLen = sIn.read(bBuffer)) > 0)
{
sOut.write(bBuffer, 0, nLen);
}
// Flush
sOut.flush();
}
finally
{
// Close streams
try
{
if (sIn != null)
sIn.close();
if (sOut != null)
sOut.close();
}
catch (IOException eError)
{
}
}
}
[/java]

For even faster results, use Channels and NIO !
The source is as small, and you use native streams while beiing “pure java”.
Umm…why not just use commons-io’s FileUtils.copyFile() method?
That is possible if you want to use a library, I needed a quick and dirty file copy.
hungarian notation…(gasp)…… catching Exception……(gurgle)…
(dies)
Always close your files in a finally block…
Good point, I should revise this.
as others noted,
- close the streams in finaly block (for not quick and dirty solutions)
- maybe the method parameters should be URI or File instead of strings only.
- i dont think you need to flush the output stream.
- in case of an exception you return false.. i would prefer a void return and throw an IOException.
Because of the snippets like these that are copy-pasted from the Google searchers we have a lot of bad code. Not closing the streams in the finally block? Catching Exception instead of the specific exceptions thrown in the code? Man…
I understand your point, I will get around to cleaning it up some. This for a little script I needed once, but still I understand your concerns.
Revision 2 has been posted, Thanks!
if an exception occurs in “sIn.close();” , sOut can be not closed.
I think that closing statements should be inside seperated try catch blocks.
Thx for the snippets.