Writing to a Channel with a ByteBuffer - Java File Path IO

Java examples for File Path IO:ByteBuffer

Description

Writing to a Channel with a ByteBuffer

Demo Code

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;

public class Main {
  void m() throws Exception {
    try {//from w  w w .j a  v a  2  s  .  co m
      WritableByteChannel channel = new FileOutputStream("outfilename")
          .getChannel();

      ByteBuffer buf = ByteBuffer.allocateDirect(10);

      byte[] bytes = new byte[1024];
      int count = 0;
      int index = 0;

      FileInputStream inputStream = new FileInputStream("infilename");
      
      while (count >= 0) {
        if (index == count) {
          count = inputStream.read(bytes);
          index = 0;
        }

        while (index < count && buf.hasRemaining()) {
          buf.put(bytes[index++]);
        }

        buf.flip();

        // Write the bytes to the channel
        int numWritten = channel.write(buf);

        // Check if all bytes were written
        if (buf.hasRemaining()) {
          buf.compact();
        } else {
          // Set the position to 0 and the limit to capacity
          buf.clear();
        }
      }
      channel.close();
    } catch (Exception e) {
    }
  }
}

Related Tutorials