Tuesday, 4 June 2019

NIO:Buffers, Channels and Selectors

Buffers, Channels and Selectors are core building blocks of NIO.

Buffer: It is a container that holds some data. A buffer can be stored in JVM heap or outside of the heap, so it does not have any impact on garbage collection.

Channel: It is the actual component, where the data comes from. A channel object connects to the file, socket etc., Channels are analogous to the streams in IO. All the data should go via channels. If you send any data to channel, the data is placed in a buffer. Any data that is read from a channel is read into a buffer.

Selectors: Used to perform asynchronous operations.

How the read operation works?
Read operation read data from a channel and write to a buffer.

Test.java
package com.sample.app;

import static java.nio.file.StandardOpenOption.READ;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Paths;

public class Test {

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

    public static void printFileContents(String filePath) throws IOException {
        FileChannel channel = FileChannel.open(Paths.get(FILE_PATH), READ);

        ByteBuffer buffer = ByteBuffer.allocate(100);

        while (channel.read(buffer) != -1) {
            buffer.flip();
            System.out.println(Charset.defaultCharset().decode(buffer));
            buffer.clear();
        }

        channel.close();

    }

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


How the write operation works?
Write operation takes data from a buffer and write to the channel.

Test.java

package com.sample.app;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Test {

 private static final String FILE_PATH = "C:\\Users\\krishna\\Documents\\Study\\demo.txt";
 
 public static void writeContentToFile(String content, String filePath) throws FileNotFoundException, IOException {
  if (content == null) {
   return;
  }

  if (filePath == null || filePath.isEmpty()) {
   throw new IllegalArgumentException("filePath shouldn't be null or empty");
  }

  try (FileOutputStream fout = new FileOutputStream(filePath)) {

   byte[] contentBytes = content.getBytes();
   ByteBuffer byteBuffer = ByteBuffer.allocate(contentBytes.length);
   byteBuffer.put(contentBytes);

   FileChannel fileChannel = fout.getChannel();
   byteBuffer.flip();
   fileChannel.write(byteBuffer);
  }

 }

 public static void main(String... args) throws IOException {
  writeContentToFile("Hello, How are you", FILE_PATH);
 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment