Example usage for java.nio MappedByteBuffer rewind

List of usage examples for java.nio MappedByteBuffer rewind

Introduction

In this page you can find the example usage for java.nio MappedByteBuffer rewind.

Prototype

@Override
public final MappedByteBuffer rewind() 

Source Link

Usage

From source file:pyromaniac.IO.MMFastqImporter.java

/**
 * Helper function for init(). Scans this.fastq file for sequence starts and records their position.
 * Multiple MappedByteBuffers are used to handle large files.
 * @throws Exceptions relating to file reading and decoding.
 *//*from w w  w . ja v  a 2  s .c  o m*/
private void _initFile() throws Exception {
    FileInputStream tempStream = new FileInputStream(new File(this.fastqFile));
    FileChannel fcSeq = tempStream.getChannel();
    this.seqSizeLong = fcSeq.size();
    this.recordStarts = new ArrayList<Pair<Integer, Long>>();

    int state = -1;

    for (long startPosition = 0L; startPosition < this.seqSizeLong; startPosition += HALF_GIGA) {
        MappedByteBuffer recordBuffer = fcSeq.map(FileChannel.MapMode.READ_ONLY, startPosition,
                Math.min(this.seqSizeLong - startPosition, HALF_GIGA));
        this.recordBuffers.add(recordBuffer);

        int sbf_pos = this.recordBuffers.size() - 1;

        int maxBuffer = 2048;
        int bufferSize = (recordBuffer.capacity() > maxBuffer) ? maxBuffer : recordBuffer.capacity();

        recordBuffer.limit(bufferSize);
        recordBuffer.position(0);

        while (recordBuffer.position() != recordBuffer.capacity()) {
            int prevPos = recordBuffer.position();
            CharBuffer result = decoder.decode(recordBuffer);
            recordBuffer.position(prevPos);

            for (int i = 0; i < result.capacity(); i++) {
                char curr = result.charAt(i);
                int posInFile = prevPos + i;

                //I see a fastq header, I am either at beginning of file, or last saw the quality line...
                if (curr == BEGINNING_FASTQ_SEQ && (state == -1 || state == 4)) {
                    this.recordStarts.add(new Pair<Integer, Long>(sbf_pos, new Long(posInFile)));
                    state = 1;

                } else if (curr == BEGINNING_FASTQ_QUAL && (state == 1)) {
                    state = 2;
                } else if ((curr == '\n' || curr == '\r') & state == 2) {
                    state = 3;
                } else if ((curr == '\n' || curr == '\r') & state == 3) {
                    state = 4;
                }
            }

            int newPos = recordBuffer.limit();

            if (recordBuffer.limit() + bufferSize > recordBuffer.capacity())
                recordBuffer.limit(recordBuffer.capacity());
            else
                recordBuffer.limit(recordBuffer.limit() + bufferSize);
            recordBuffer.position(newPos);
        }
        recordBuffer.rewind();
    }
}