How to copy a file


 

How to copy a file

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

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.

Ads