Sunday 16 June 2019

NIO: Reading and writing to Multiple Buffers


Step 1: Create buffers.
ByteBuffer buffer1 = ByteBuffer.allocate(1024);
ByteBuffer buffer2 = ByteBuffer.allocate(1024);
ByteBuffer buffer3 = ByteBuffer.allocate(1024);

Step 2: Write some content to the buffers.
buffer1.put(new String("content from file1\n").getBytes());
buffer2.put(new String("content from file2\n").getBytes());
buffer3.put(new String("content from file3\n").getBytes());

Step 3: Flip the buffers..
buffer1.flip();
buffer2.flip();
buffer3.flip();

Step 4: Create ByteBuffer array and write the buffer array to channel.
ByteBuffer[] buffers = {buffer1, buffer2, buffer3};
FileChannel channel = FileChannel.open(Paths.get(FILE_PATH), CREATE, WRITE);
channel.write(buffers);

Test.java
package com.sample.app;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Paths;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.WRITE;


public class Test {

 private static final String FILE_PATH = "/Users/krishna/Documents/demo.txt";

 public static void main(String... args) throws IOException {
  ByteBuffer buffer1 = ByteBuffer.allocate(1024);
  ByteBuffer buffer2 = ByteBuffer.allocate(1024);
  ByteBuffer buffer3 = ByteBuffer.allocate(1024);
  
  buffer1.put(new String("content from file1\n").getBytes());
  buffer2.put(new String("content from file2\n").getBytes());
  buffer3.put(new String("content from file3\n").getBytes());
  
  buffer1.flip();
  buffer2.flip();
  buffer3.flip();
  
  ByteBuffer[] buffers = {buffer1, buffer2, buffer3};
  
  FileChannel channel = FileChannel.open(Paths.get(FILE_PATH), CREATE, WRITE);
  channel.write(buffers);
  
  channel.close();
  
 }
}

Run Test.java and open demo.txt you can see below content.
$cat demo.txt
content from file1
content from file2

content from file3



Previous                                                 Next                                                 Home

No comments:

Post a Comment