Read byte array out of a file with FileChannel in Java

Description

The following code shows how to read byte array out of a file with FileChannel.

Example


/*from   ww w  .  j av a  2 s .c o  m*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
  private static final int BSIZE = 1024;

  public static void main(String[] args) throws Exception {

    FileChannel fc = new FileOutputStream("main.java").getChannel();
    fc.write(ByteBuffer.wrap("Some text ".getBytes()));
    fc.close();


    fc = new RandomAccessFile("main.java", "rw").getChannel();
    fc.position(fc.size()); // Move to the end
    fc.write(ByteBuffer.wrap("Some more".getBytes()));
    fc.close();


    fc = new FileInputStream("main.java").getChannel();
    ByteBuffer buff = ByteBuffer.allocate(BSIZE);
    fc.read(buff);
    buff.flip();
    while (buff.hasRemaining()){
      System.out.print((char) buff.get());
      }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip