Share on Google+Share on Google+

How to copy a file

Advertisement
In this section, you will learn how to copy a file using Java IO library.

How to copy a file

In this section, you will learn how to copy a file using Java IO library. For this, we have declared a function called copyfile() which creates two File instances to specify source and destination file respectively. It then creates InputStream instance for the input object and OutputStream instance for the output object. The read() method of an InputStream class  reads the byte value from the stream until there is a data in the stream from the source file. The write() method of OutputStream class writes this value into the destination file.

Here is the code:

import java.io.*;

public class CopyFile {
  private static void copyfile() {
    try {
      File f1 = new File("C:/file.txt");
      File f2 = new File("C:/new.txt");
      InputStream in = new FileInputStream(f1);
      OutputStream out = new FileOutputStream(f2, true);
      byte[] buf = new byte[1024];
      int len;
      while ((len = in.read(buf)) 0) {
        out.write(buf, 0, len);
      }
      in.close();
      out.close();
      System.out.println("File copied.");
    catch (Exception ex) {
      System.out.println(ex);
    }
  }

  public static void main(String[] args) {
    copyfile();
  }
}

The above code makes a copy of the file.

Advertisements

Advertisement

Posted on: April 3, 2006 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.