• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 231
  • Last Modified:

How to do a quick file copy

I have a file c:\directory1\file1.mdb
that I want to copy to c:\directory2 and overwrite file1.mdb in directory2 if it exists in there.
How is this done in java?
1 Solution
Write a batch file and execute it from your Java app :-)
Java does not have a specific method for copying a file, the only way to do is to read the existing file, and write the new one.
It is easy to do it yourself:
public static void copyFile(File f1, File f2) throws IOException {
    FileInputStream in = new FileInputStream(f1);
    FileOutputStream out = new FileOutputStream(f2);
    byte[] buf = new byte[2048];
    int r;
    while ((r=in.read(buf)) != -1) {
        out.write(buf, 0, r);
public static void copy(File f1, File f2) throws IOException {
    if (f1.isDirectory()) {
        String[] files = f1.list();
        for (int i =0; i < files.length; i++) {
            copy(new File(f1, files[i]), new File(f2, files[i]));
    } else {
        copyFile(f1, f2);
public static void copy(String f1, String f2) throws IOException {
    copy(new File(f1), new File(f2));

Use it this way:
try {
  copy("c:/ivv", "c:/ivv_copy");
} catch (IOException ioe) {
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now