Friday, March 18, 2011

How to copy file ?

Java provides two classes for reading from and writing to a file.

FileInputStream is for reading binary file.
FileOutputStream is for writing.

The following sample illustrate how to use these two classes.

This sample can copy ASCII file as well as binary file.

By default it would copy itself, you may change the name of source file and destination file in line 15 and 16.

* File :
* Author :
* Description :
*   Simple file copying
* Tested with : JDK 1.6


public class Copier
  public static void main(String[] args) throws Exception
    String source_file="";  // copy myself
    String dest_file = "";  // name of the copy
    FileInputStream fis=new FileInputStream(source_file);
    FileOutputStream fos=new FileOutputStream(dest_file);

    int BUF_SIZE=1024;
    byte[] buffer=new byte[BUF_SIZE];   // 1K copy buffer
    while (true)
      int;     // read
      if (n>0) fos.write(buffer,0,n);      // copy
      if (n<0) break;      // EOF


No comments:

Post a Comment