Friday 7 June 2019

NIO: FileChannel: Reading data from a file

Below step-by-step procedure explains, how to read data from a file.

Step 1: Get the FileChannel instance from the file.
FileChannel channel = FileChannel.open(Paths.get(FILE_PATH), READ);

Step 2: Create a buffer.
ByteBuffer buffer = ByteBuffer.allocate(100);

Step 3: Read the contents of file from the channel and place the content in buffer.
while (channel.read(buffer) != -1) {
    buffer.flip();
    System.out.println(Charset.defaultCharset().decode(buffer));
    buffer.clear();
}

Step 4: Close the channel.
channel.close();

Test.java
package com.sample.app;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;


public class Test {

 private static final String FILE_PATH = "/Users/krishna/Documents/demo.txt";

 public static void printFileContents(String filePath) throws IOException {
  try (FileInputStream fin = new FileInputStream(filePath)) {
   FileChannel fileChannel = fin.getChannel();

   ByteBuffer buffer = ByteBuffer.allocate(100);

   int noOfBytesRead;

   while ((noOfBytesRead = fileChannel.read(buffer)) != -1) {
    String str = new String(buffer.array());
    System.out.println(str);
    buffer.flip();

   }

  }

 }

 
 public static void main(String... args) throws IOException {
  printFileContents(FILE_PATH);
 }
}



Previous                                                 Next                                                 Home

No comments:

Post a Comment