Solved

How to do a quick file copy

Posted on 2002-03-05
3
187 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

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
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.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This video teaches viewers about errors in exception handling.

760 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

21 Experts available now in Live!

Get 1:1 Help Now