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) {      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:
data observability

Data Observability Explained

Data is the lifeblood of any successful business, as it is the driving force behind critical decision-making, insight generation, and strategic development. However, due to its intricate nature, ensuring the

Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular