Monday, April 15, 2024

Read File Asynchronously Java Program

In this post we’ll see how to read file asynchronously in Java using java.nio.channels.AsynchronousFileChannel class added in Java 7. Using AsynchronousFileChannel class you can create an asynchronous channel for reading, writing, and manipulating a file.

Opening an Asynchronous channel

Whether you are reading or writing a file asynchronously first thing you need to do is to create an asynchronous channel. For that you can use static open() method of the AsynchronousFileChannel class which opens or creates a file for reading or writing, returning an asynchronous file channel to access the file.

Following code snippet shows how you can create an asynchronous file channel for reading a file.

Path path = Paths.get("F:\\netjs\\test.txt");
AsynchronousFileChannel asyncFileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ)

Reading file asynchronously using AsynchronousFileChannel class

For reading a file asynchronously there are two versions of read() method in the AsynchronousFileChannel class.

  1. read() method that returns a Future.
  2. read() method where you can pass CompletionHandler instance as an argument.

We’ll see examples of of both of these ways to have a better idea.

Reading file asynchronously in Java

1. In the first Java program we’ll use the read method that returns a Future.

abstract Future<Integer> read(ByteBuffer dst, long position)- This method reads sequence of bytes from the opened channel into the buffer passed as argument. Reading starts at the passed file position.

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 AsyncFileRead {
  public static void main(String[] args) {
    Path path = Paths.get("F:\\netjs\\test.txt");
    // buffer into which data is read
    // increase the buffer size if required
    ByteBuffer buffer = ByteBuffer.allocate(4096);
    try(AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ)){
      Future<Integer> result = asyncChannel.read(buffer, 0);
      while(!result.isDone()) {
        System.out.println("Waiting for read... ");
        // You can do other processing
      }
      /* File data ready */
      //limit is set to the current position 
      //and position is set to zero
      buffer.flip();
      String data = new String(buffer.array()).trim();
      System.out.println(data);
      buffer.clear();            
    } catch (IOException e) {
      System.out.println("Error while reading file- " + e.getMessage());
      e.printStackTrace();
    }        
  }
}

2. In this Java program for reading file asynchronously we’ll use the read() method where CompletionHandler instance is passed as an argument.

CompletionHandler interface defines two callback methods which you need to implement.

  • completed(V result, A attachment)- Invoked when an operation has completed.
  • failed(Throwable exc, A attachment)- Invoked when an operation fails.
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.nio.channels.CompletionHandler;

public class AsyncFileRead {
  public static void main(String[] args) {
    Path path = Paths.get("F:\\netjs\\test.txt");
    // buffer into which data is read
    // increase the buffer size if required
    ByteBuffer buffer = ByteBuffer.allocate(4096);
    try(AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ)){
      asyncChannel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
        // callback methods
        @Override
        public void completed(Integer result, ByteBuffer attachment) {
          System.out.println("Number of bytes read- " + result);
          attachment.flip();
          String data = new String(attachment.array()).trim();
          System.out.println("..." + data.length());
          System.out.println(data);
          attachment.clear();
        }

        @Override
        public void failed(Throwable ex, ByteBuffer attachment) {
          System.out.println("Read operation failed- " + ex.getMessage());                
        }            
      });
      System.out.println("Asynchronous operation in progress.. Once over callback method will be called.");
    } catch (IOException e) {
      System.out.println("Error while reading file- " + e.getMessage());
      e.printStackTrace();
    }        
  }
}

That's all for this topic Read File Asynchronously Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Reading File in Java Using Files.lines And Files.newBufferedReader
  2. Reading All Files in a Folder - Java Program
  3. How to Read Properties File in Java
  4. How to Read File From The Last Line in Java
  5. How to Create PDF From XML Using Apache FOP

You may also like-

  1. Write to a File in Java
  2. Setting And Getting Thread Name And Thread ID - Java Program
  3. How to Untar a File - Java Program
  4. Converting Numbers to Words - Java Program
  5. Nested Class And Inner Class in Java
  6. Generic Class, Interface And Generic Method in Java
  7. Angular Two-Way Data Binding With Examples
  8. Magic Methods in Python With Examples