0

I am reading a file using RandomFileAccess, FileChannel and ByteBuffer as follows:

RandomAccessFile myFile = new RandomAccessFile("/Users/****/Documents/a.txt", "rw");
FileChannel myInChannel = myFile.getChannel();

ByteBuffer bb = ByteBuffer.allocate(48);

int bytesRead = myInChannel.read(bb);
while (bytesRead != -1) {
     // do something
}
myFile.close();

All this code is working fine. But i am wondering is there any way i can read the data using Future?

KayV
  • 12,987
  • 11
  • 98
  • 148
  • Are you asking how to decouple the thread that initiates a read from the thread that consumes the result through a `Future`? I ask because `FileChannel`s are likely doing a blocking synchronous call under the hood, so using a Future does not buy you anything in the way of asynchronous operations. – Gili Dec 12 '16 at 07:42
  • I am not sure if can be done via a FileChannel or not. If not, what is the alternate for that? – KayV Dec 12 '16 at 07:43
  • Sorry for asking this, but what are you trying to do? Why do you need a `Future`? Are you trying to read asynchronously using a `FileChannel`? Read my updated comment above. – Gili Dec 12 '16 at 07:44
  • I am just learning the way to implement Future while reading reading data from file. – KayV Dec 12 '16 at 07:45
  • Thanks for the clarification. I will try answering this in a minute. – Gili Dec 12 '16 at 07:46

1 Answers1

1

I tried following code, and it worked fine for:

try(AsynchronousFileChannel afileChannel = AsynchronousFileChannel.open(Paths.get("/Users/***/Documents/myFile.txt"), StandardOpenOption.READ)) {

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        long position = 0;

        Future<Integer> operation = afileChannel.read(buffer, position);

        while(!operation.isDone()){
            //do something
        }

        buffer.flip();
        byte[] data = new byte[buffer.limit()];
        buffer.get(data);
        System.out.println(new String(data));

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Got to know that this can be done via AsynchronousFileChannel but not via FileChannel.

KayV
  • 12,987
  • 11
  • 98
  • 148
  • Yes. That'll do it :) – Gili Dec 12 '16 at 07:58
  • I have a scenario where I need to do something after every buffer is read. I don't need to bother about it not being sequential. So Do I need to add my step of work into the while loop while(!operation.isDone()){}, will the control enter here once the thread reads the allocated Bytes? – mwKART Jun 17 '22 at 05:57