Java FileChannel for read and write create from stream and RandomAccessFile

Description

Java FileChannel for read and write create from stream and RandomAccessFile

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;

public class Main {
  public static void main(String[] args) throws Exception {
    FileInputStream fis = new FileInputStream("Main.java");
    FileChannel fcReadOnly = fis.getChannel(); // A read-only channel

    FileOutputStream fos = new FileOutputStream("Main.java");
    FileChannel fcWriteOnly = fos.getChannel(); // A write-only channel

    // Open file in a read-only mode
    RandomAccessFile raf1 = new RandomAccessFile("Main.java", "r");
    FileChannel rafReadOnly = raf1.getChannel(); // A read-only channel

    // Open file in a read-write mode
    RandomAccessFile raf2 = new RandomAccessFile("Main.java", "rw");
    FileChannel rafReadWrite = raf2.getChannel(); // A read-write channel


  }/*from w  ww  . java  2 s  .  c o  m*/
}



PreviousNext

Related