Home  >  Core Java

Example of FileChannel in Java NIO Channels

By Arvind Rai, November 20, 2013
FileChannel belongs to the package java.nio.channels and do reading, writing and updating the files. FileChannel keeps a current position that can be modified. FileChannel can do even more task. It can read and write bytes, transfer byte to other channel and can lock some part of file if required. FileChannel is thread safe in multithreaded environment. Find an example which will read a file.

FileChannelTest.java
package com.concretepage.nio.channels;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class FileChannelTest {
  public static void main(String[] args) throws IOException {
      FileInputStream fin = null;
      FileChannel fchannel = null;
      try{
        //opens a file to read from the given location
        fin = new FileInputStream("C:/temp/test.txt");
        
        //returns FileChannel instance to read the file
        fchannel = fin.getChannel();   
        
        //allocate byte buffer size
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        
        while(fchannel.read(byteBuffer) > 0){
            
            //limit is set to current position and position is set to zero
            byteBuffer.flip();
            
            while(byteBuffer.hasRemaining()){
                char ch = (char) byteBuffer.get();
                System.out.print(ch);
            }
            
            //position is set to zero and limit is set to capacity to clear the buffer.
            byteBuffer.clear();
        }
      }catch(IOException e){
          e.printStackTrace();
      }finally{
          fin.close();
          fchannel.close();
      }
  }
}
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us