FileChannel

A channel for reading, writing, mapping, and manipulating a file.

A file channel has a current position within its file which can be both queried and modified. File channels are safe for use by multiple concurrent threads.

FileChannel.MapMode.READ_ONLY defines a mode for a read-only mapping.


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);
    }
  }
}
Home 
  Java Book 
    File Stream  

FileChannel:
  1. FileChannel
  2. FileChannel.MapMode.READ_WRITE
  3. FileChannel: close()
  4. FileChannel: lock(long position, long size, boolean shared)
  5. FileChannel: map(MapMode mode, long position, long size)
  6. FileChannel: position()
  7. FileChannel: position(long newPosition)
  8. FileChannel: read(ByteBuffer dst)
  9. FileChannel: size()
  10. FileChannel: transferFrom(ReadableByteChannel src, long position, long count)
  11. FileChannel: transferTo(long position, long count, WritableByteChannel target)
  12. FileChannel: tryLock()
  13. FileChannel: write(MappedByteBuffer buffer)