package com.chenyang.nse.bussiness.tools.dmp;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ChannelFileReader {
   private FileInputStream fileIn;
   private ByteBuffer byteBuf;
   private long fileLength;
   private int arraySize;
   private byte[] array;

   public ChannelFileReader(String fileName, int arraySize) throws IOException {
      this.fileIn = new FileInputStream(fileName);
      this.fileLength = this.fileIn.getChannel().size();
      this.arraySize = arraySize;
      this.byteBuf = ByteBuffer.allocate(arraySize);
   }

   public int read() throws IOException {
      FileChannel fileChannel = this.fileIn.getChannel();
      int bytes = fileChannel.read(this.byteBuf);
      if (bytes != -1) {
         this.array = new byte[bytes];
         this.byteBuf.flip();
         this.byteBuf.get(this.array);
         this.byteBuf.clear();
         return bytes;
      } else {
         return -1;
      }
   }

   public void close() throws IOException {
      this.fileIn.close();
      this.array = null;
   }

   public byte[] getArray() {
      return this.array;
   }

   public long getFileLength() {
      return this.fileLength;
   }

   public static void main(String[] args) throws IOException {
      ChannelFileReader reader = new ChannelFileReader("/home/zfh/movie.mkv", 65536);
      long start = System.nanoTime();

      while(reader.read() != -1) {
      }

      long end = System.nanoTime();
      reader.close();
      System.out.println("ChannelFileReader: " + (end - start));
   }
}
