LongBuffer: position() : LongBuffer « java.nio « Java by API






LongBuffer: position()

 
import static java.lang.Math.ceil;
import static java.lang.Math.min;
import static java.lang.Math.sqrt;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.LongBuffer;
import java.nio.channels.FileChannel;

public class MainClass {
  public static void main(String[] args) {
    int count = 100;

    long[] numbers = new long[count];

    for (int i = 0; i < numbers.length; i++) {
      numbers[i] = i;

    }
    File aFile = new File("data.bin");
    FileOutputStream outputFile = null;
    try {
      outputFile = new FileOutputStream(aFile);
    } catch (FileNotFoundException e) {
      e.printStackTrace(System.err);
      System.exit(1);
    }
    FileChannel file = outputFile.getChannel();
    final int BUFFERSIZE = 100;
    ByteBuffer buf = ByteBuffer.allocate(BUFFERSIZE);
    LongBuffer longBuf = buf.asLongBuffer();

    int numberWritten = 0;

    while (numberWritten < numbers.length) {
      longBuf.put(numbers, numberWritten, min(longBuf.capacity(), numbers.length - numberWritten));
      buf.limit(8 * longBuf.position());
      try {
        file.write(buf);
        numberWritten += longBuf.position();
      } catch (IOException e) {
        e.printStackTrace(System.err);
        System.exit(1);
      }
      longBuf.clear();
      buf.clear();
    }

    try {
      System.out.println("File written is " + file.size() + " bytes.");
      outputFile.close();
    } catch (IOException e) {
      e.printStackTrace(System.err);
      System.exit(1);
    }
  }
}

           
         
  








Related examples in the same category

1.LongBuffer: clear()
2.LongBuffer: get()
3.LongBuffer: get(long[] dst)
4.ShortBuffer: hasRemaining()
5.LongBuffer: put(long l)
6.LongBuffer: put(long[] src, int offset, int length)
7.LongBuffer: remaining()