Tuesday 2 February 2021

How to read contents of file asynchronously?

 

'java.nio.channels.AsynchronousFileChannel' provides 'read' method to read the contents of a file asynchronously.

 

‘read’ method is available in two overloaded forms.

public abstract Future<Integer> read(ByteBuffer dst, long position)

Reads a sequence of bytes from this channel into the given buffer, starting at the given file position. This method return a Future object which represent pending result.

 

Parameters:

a.   dst - The buffer into which bytes are to be transferred

b.   position - The file position at which the transfer is to begin; must be non-negative

Returns:

         A Future object representing the pending result

 

public abstract <A> void read(ByteBuffer dst, long position, A attachment, CompletionHandler<Integer,? super A> handler)

Reads a sequence of bytes from this channel into the given buffer, starting at the given file position.

 

Parameters:

a.   dst - The buffer into which bytes are to be transferred

b.   position - The file position at which the transfer is to begin; must be non-negative

c.    attachment - The object to attach to the I/O operation; can be null

d.   handler - The handler for consuming the result

 

‘CompletionHandler’ interface has two callback methods.

a.   completed: Invoked when an operation has completed.

b.   failed: Invoked when an operation fails.

 

Example using read method

FileReadAsynchronousDemo1.java

package com.sample.app;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;

public class FileReadAsynchronousDemo1 {

	public static void main(String args[]) {
		String filePath = "/Users/krishna/Documents/empInfo.txt";
		Path path = Paths.get(filePath);

		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

		try (AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ)) {
			Future<Integer> bytesRead = asyncChannel.read(byteBuffer, 0);
	
			// Wait until file content read to byteBuffer
			while (!bytesRead.isDone()) {
				System.out.println("Read operation is in progress.......");
			}

			byteBuffer.flip();
			String data = new String(byteBuffer.array());
			System.out.println(data);
			byteBuffer.clear();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

 

Using read method and completion handler

FileReadAsynchronousDemo2.java

package com.sample.app;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.TimeUnit;

public class FileReadAsynchronousDemo2 {
	public static void main(String args[]) throws InterruptedException {
		String filePath = "/Users/krishna/Documents/empInfo.txt";
		Path path = Paths.get(filePath);

		ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

		try (AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ)) {
			asyncChannel.read(byteBuffer, 0, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {

				@Override
				public void completed(Integer result, ByteBuffer attachment) {
					System.out.println("Number of bytes read : " + result);
					attachment.flip();
					String data = new String(attachment.array());
					System.out.println(data);
					attachment.clear();
				}

				@Override
				public void failed(Throwable exc, ByteBuffer attachment) {
					System.out.println("Read operation failed with error : " + exc.getMessage());
				}

			});
			System.out.println("Waiting for the asynchronous file read operation");

			TimeUnit.SECONDS.sleep(5);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment