• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us

Reading file asynchronously in Java

August 22, 2012 //  by Mohamed Sanaulla

We all are familiar with reading/writing file in a synchronous way. In Java 7 a new API was added to read/write the contents of the file asynchronously. The API is AsynchronousFileChannel.

also read:

  • Java 7.0 Tutorials
  • New Features in Java 7.0
  • G1 Garbage Collector in Java 7.0

In this example lets look at how to read the contents of the file asynchronously. There are two approaches to read the contents asynchronously:
1. To use Future class to wait for the result of the read operation.
2. To use a callback defined by the CompletionHandler to process the result of the Asynchronous operation.

//Using Future class to read the contents of the file.
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.charset.Charset;
import java.nio.file.*;
import java.util.concurrent.*;

public class AsyncFutureRead {

  public static void main(String[] args) {

    //Buffer to read the contents from the file.
    ByteBuffer buffer = ByteBuffer.allocate(100);

    //The file to read the contents from.
    Path path = Paths.get('D:/tests/test.txt');

    //Creating the asynchronous channel to the file which allows reading and writing of content.
    try(AsynchronousFileChannel asyncChannel = AsynchronousFileChannel.open(path)){

      //Returns a Future instance which can be used to read the contents of the file.
      Future<Integer> fileResult = asyncChannel.read(buffer, 0);

      //Waiting for the file reading to complete.
      while(!fileResult.isDone()){
        System.out.println('Waiting to complete the file reading ...');
      }

      //Print the number of bytes read.
      System.out.println('Number of bytes read: '+fileResult.get());

      //Reset the current position of the buffer to the beginning and the limit to the current position.
      buffer.flip();

      //Decode the contents of the byte buffer.
      System.out.println('Contents of file: ');
      System.out.println(Charset.defaultCharset().decode(buffer));

    }catch(IOException | InterruptedException | ExecutionException ex){
      ex.printStackTrace();
    }
  }
}

Pro Java 7 NIO.2 addresses the three primary elements that offer new input/output (I/O) APIs in Java 7, giving you the skills to write robust, scalable Java applications.

Category: JavaTag: java 7, Java nio

About Mohamed Sanaulla

In his day job he works on developing enterprise applications using ADF. He is also the moderator of JavaRanch forums and an avid blogger.

Previous Post: « How to use ByteBuffer in Java?
Next Post: Execute batch file or shell script using Ant »

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

How to Initialize an Array in Java

Introduction to Java Server Faces (JSF)

Introduction to Java 6.0 New Features, Part–1

Java 6.0 Features Part – 2 : Pluggable Annotation Processing API

Introduction to Java Server Faces(JSF) HTML Tags

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact