集册 Java实例教程 用ByteBuffer写入通道

用ByteBuffer写入通道

欢马劈雪     最近更新时间:2020-01-02 10:19:05

715
用ByteBuffer写入通道

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.nio.ByteBuffer;/**from nowjava.com - 时  代  Java**/

import java.nio.channels.WritableByteChannel;


public class Main {

  void m() throws Exception {

    try {

      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) {
      /**
      来 自 时代Java公众号
      **/

        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.has
展开阅读全文