Showing posts with label asynchronously. Show all posts
Showing posts with label asynchronously. Show all posts

Tuesday, 2 February 2021

Write to a file asynchronously in Java

 

Using ‘AsynchronousFileChannel’ write method, you can write to a file asynchronously in Java.

 

‘write’ method is available in two overloaded forms.

 

public abstract Future<Integer> write(ByteBuffer src, long position)

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

 

Parameters:

a.   src - The buffer from 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 write(ByteBuffer src, long position, A attachment, CompletionHandler<Integer,? super A> handler)

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

 

Parameters:

a.   src - The buffer from 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 write method

FileWriteAsynchronousDemo1.java

package com.sample.app;

import java.io.File;
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.ExecutionException;
import java.util.concurrent.Future;

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

		File file = path.toFile();
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
				System.exit(0);
			}
		}

		ByteBuffer buffer = ByteBuffer.allocate(1024);
		buffer.put("Hello World".getBytes());

		buffer.flip();

		try (AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE)) {

			Future<Integer> future = asyncChannel.write(buffer, 0);
			while (!future.isDone()) {
				System.out.println("Write operation is still pending!!!!!");
			}
			buffer.clear();

			System.out.println("Write operation finished, bytes written : " + future.get());
		} catch (IOException | InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
	}

}

Example using write method and CompletionHandler

FileWriteAsynchronousDemo2.java

package com.sample.app;

import java.io.File;
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 FileWriteAsynchronousDemo2 {
	public static void main(String[] args) {
		Path path = Paths.get("/Users/krishna/Documents/b.txt");

		File file = path.toFile();
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
				System.exit(0);
			}
		}

		ByteBuffer buffer = ByteBuffer.allocate(1024);
		buffer.put("Hello World".getBytes());

		buffer.flip();

		try (AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE)) {

			asyncChannel.write(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {

				@Override
				public void completed(Integer result, ByteBuffer attachment) {
					System.out.println("Write operation finished, number of bytes written: " + result);
					attachment.clear();
				}

				@Override
				public void failed(Throwable exc, ByteBuffer attachment) {
					System.out.println("Write operation failed: " + exc.getMessage());
				}
			});
			
			System.out.println("Wait for some time....");
			TimeUnit.SECONDS.sleep(5);
		} catch (IOException| InterruptedException e) {
			e.printStackTrace();
		}
	}

}




 

 

Previous                                                    Next                                                    Home

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