Home Tutorial Java Core Files How to copy a file

 
 

Share on Google+Share on Google+
How to copy a file
Posted on: April 3, 2006 at 12:00 AM
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.

Advertisement

Related Tags for How to copy a file:


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.

Posted on: April 3, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com