Java File Read via ByteBuffer skip(final ReadableByteChannel input, final long toSkip)

Here you can find the source of skip(final ReadableByteChannel input, final long toSkip)

Description

Skips bytes from a ReadableByteChannel.

License

Open Source License

Parameter

Parameter Description
input ReadableByteChannel to skip
toSkip number of bytes to skip.

Exception

Parameter Description
IOExceptionif there is a problem reading the ReadableByteChannel
IllegalArgumentException if toSkip is negative

Return

number of bytes actually skipped.

Declaration

public static long skip(final ReadableByteChannel input, final long toSkip) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;
import java.nio.ByteBuffer;

import java.nio.channels.ReadableByteChannel;

public class Main {
    private static final int EOF = -1;

    /**/*  w  w w . jav a 2 s. c o m*/
     * Skips bytes from a ReadableByteChannel.
     * This implementation guarantees that it will read as many bytes
     * as possible before giving up.
     *
     * @param input  ReadableByteChannel to skip
     * @param toSkip number of bytes to skip.
     * @return number of bytes actually skipped.
     * @throws IOException              if there is a problem reading the ReadableByteChannel
     * @throws IllegalArgumentException if toSkip is negative
     * @since 2.5
     */
    public static long skip(final ReadableByteChannel input, final long toSkip) throws IOException {

        final int SKIP_BUFFER_SIZE = 2048;

        if (toSkip < 0) {
            throw new IllegalArgumentException("Skip count must be non-negative, actual: " + toSkip);
        }
        final ByteBuffer skipByteBuffer = ByteBuffer.allocate((int) Math.min(toSkip, SKIP_BUFFER_SIZE));
        long remain = toSkip;
        while (remain > 0) {
            skipByteBuffer.position(0);
            skipByteBuffer.limit((int) Math.min(remain, SKIP_BUFFER_SIZE));
            final int n = input.read(skipByteBuffer);
            if (n == EOF) {
                break;
            }
            remain -= n;
        }
        return toSkip - remain;
    }
}

Related

  1. readVarLong(byte[] arr)
  2. readWaveFile44100_16Bit_Mono(String dir, String name)
  3. readWavHeader(DataInputStream inStrm, FileChannel fc)
  4. readWholeFile(File file, StringBuilder stringBuilder)
  5. readZipComment(File file)
  6. streamRead(SocketChannel in)