Copy a file using NIO : New IO « File Input Output « Java






Copy a file using NIO

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class MainClass {

  public static void main(String args[]) {
    FileInputStream fIn;
    FileOutputStream fOut;
    FileChannel fIChan, fOChan;
    long fSize;
    MappedByteBuffer mBuf;

    try {
      fIn = new FileInputStream(args[0]);
      fOut = new FileOutputStream(args[1]);

      fIChan = fIn.getChannel();
      fOChan = fOut.getChannel();

      fSize = fIChan.size();

      mBuf = fIChan.map(FileChannel.MapMode.READ_ONLY, 0, fSize);

      fOChan.write(mBuf); // this copies the file

      fIChan.close();
      fIn.close();

      fOChan.close();
      fOut.close();
    } catch (IOException exc) {
      System.out.println(exc);
      System.exit(1);
    } catch (ArrayIndexOutOfBoundsException exc) {
      System.out.println("Usage: Copy from to");
      System.exit(1);
    }
  }
}

           
       








Related examples in the same category

1.Use a mapped file to read a text file
2.FileChannel: map(FileChannel.MapMode mode,long position,long size)
3.Write to a file using the new I/O
4.Write to a mapped file
5.Write A String As Bytes
6.Use New Java IO to write string into a file