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

No comments:

Post a Comment