Solved

How to do a quick file copy

Posted on 2002-03-05
3
194 Views
Last Modified: 2010-08-05
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?
0
Comment
Question by:tom_corc
3 Comments
 
LVL 18

Expert Comment

by:bobbit31
ID: 6842303
0
 
LVL 92

Expert Comment

by:objects
ID: 6842387
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.
0
 
LVL 9

Accepted Solution

by:
Venci75 earned 200 total points
ID: 6843715
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()) {
        f2.mkdirs();
        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) {
  ioe.printStackTrace();
}
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This video teaches viewers about errors in exception handling.

932 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now