Skip to content

Instantly share code, notes, and snippets.

@Forkk
Created January 7, 2012 19:08
Show Gist options
  • Save Forkk/1575676 to your computer and use it in GitHub Desktop.
Save Forkk/1575676 to your computer and use it in GitHub Desktop.
Copy file
public static void copyFile(File source, File dest, boolean overwrite)
throws IOException
{
if (!overwrite && dest.exists())
throw new IOException("Can't copy " + source + " to " + dest + ". " +
"The file already exists.");
if (source.isDirectory())
throw new IOException("Can't copy directories! Use recursiveCopy() " +
"instead.");
else if (overwrite && dest.exists())
dest.delete();
dest.createNewFile();
// Declare input streams
FileInputStream fIn = null;
BufferedInputStream in = null;
// Declare output streams
FileOutputStream fOut = null;
BufferedOutputStream out = null;
final int bufferSize = 512;
try
{
fIn = new FileInputStream(source);
in = new BufferedInputStream(fIn, bufferSize);
fOut = new FileOutputStream(dest);
out = new BufferedOutputStream(fOut, bufferSize);
int count = 0;
byte[] buffer = new byte[bufferSize];
while ((count = in.read(buffer, 0, buffer.length)) >= 0)
{
out.write(buffer, 0, count);
}
out.flush();
} finally
{
// Make sure streams and channels get closed.
if (in != null)
in.close();
else if (fIn != null)
fIn.close();
if (out != null)
out.close();
else if (fOut != null)
fOut.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment