Copying Files

Copying Files

Is there a simple way of copying a file from one directory to another?

There is no predefined convenient method for copying a file from oneplace to another. You have to do it the old fashioned way.

Open thesource file, open the destination file, read the source file a chunkat a time into a buffer, and write the buffer to the destination file.Here is some sample code for doing that, with minimal error checking:

import*;public class copy {  public static final int BUFFER_SIZE = 4096;  public static final void copyStream(InputStream input, OutputStream output,                                      byte[] buffer)    throws IOException  {    int bytesRead;    while((bytesRead = != -1)      output.write(buffer, 0, bytesRead);  }  public static final void main(String[] args) {    byte[] buffer = new byte[BUFFER_SIZE];    BufferedInputStream input;    BufferedOutputStream output;    File destination;    if(args.length  2 || destination.isDirectory()) {        if(!destination.isDirectory()) {          System.err.println(     "When copying multiple files, last argument must be a directory.");          return;        }        for(int i=0; i 

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist