Java File Read via ByteBuffer count(final ReadableByteChannel src)

Here you can find the source of count(final ReadableByteChannel src)

Description

Reads data from an input stream counting the number of bytes.

License

Open Source License

Parameter

Parameter Description
src the source to read from

Exception

Parameter Description
IOException if an I/O error occurs

Return

the number of bytes read

Declaration

public static long count(final ReadableByteChannel src) throws IOException 

Method Source Code


//package com.java2s;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

public class Main {
    /**//from   www  .ja va 2 s  .c o  m
     * Default buffer size used when no buffer sizes is provided. Default is 16KB.
     */
    public static final int DEFAULT_BUFFER_SIZE = 16 * 1024;

    /**
     * Reads data from an input stream counting the number of bytes.
     *
     * @param src the source to read from
     * @return the number of bytes read
     * @throws IOException if an I/O error occurs
     */
    public static long count(final ReadableByteChannel src) throws IOException {
        final ByteBuffer buf = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE);
        long count = 0;
        int read = 0;
        while ((read = src.read(buf)) != -1) {
            count += read;
            buf.clear();
        }
        return count;
    }

    /**
     * Reads data from an input stream counting the number of bytes.
     *
     * @param src the source to read from
     * @return the number of bytes read
     * @throws IOException if an I/O error occurs
     */
    public static long count(final InputStream src) throws IOException {
        return count(Channels.newChannel(src));
    }
}

Related

  1. ClientReadWithWait(SocketChannel sc)
  2. copy(final ReadableByteChannel src, final WritableByteChannel dest)
  3. copy(final ReadableByteChannel srcChannel, final WritableByteChannel destChannel)
  4. copyChannel(int bufferSize, ReadableByteChannel source, WritableByteChannel destination)
  5. copyStream(BufferedReader reader, BufferedWriter writer)
  6. getReadBuffer(File file)
  7. getStringContents(ReadableByteChannel channel)
  8. largeFileReader(String filename)
  9. mapReadWrite(File file)