Copying Files

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

Answer:
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 java.io.*;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 = input.read(buffer)) != -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) {      System.err.println("Usage: copy file1 file2 ... dest");      return;    }    try {       destination = new File(args[args.length - 1]);      buffer = new byte[BUFFER_SIZE];      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 < (args.length - 1); ++i) {          File inFile;          inFile = new File(args[i]);          input =            new BufferedInputStream(new FileInputStream(inFile));          output =            new BufferedOutputStream(new FileOutputStream(                        new File(destination, inFile.getName())));          copyStream(input, output, buffer);          input.close();          output.close();        }      } else {        input =          new BufferedInputStream(new FileInputStream(args[0]));        output =          new BufferedOutputStream(new FileOutputStream(destination));        copyStream(input, output, buffer);        input.close();        output.close();      }    } catch(IOException ioe) {      ioe.printStackTrace();      return;    }  }}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: