Java File Read via ByteBuffer read(final FileChannel channel)

Here you can find the source of read(final FileChannel channel)

Description

Reads all data from the given file channel.

License

Open Source License

Parameter

Parameter Description
channel File channel to read.

Exception

Parameter Description
IOExceptionOn read errors.

Return

Entire contents of channel.

Declaration

public static byte[] read(final FileChannel channel) throws IOException 

Method Source Code


//package com.java2s;
/*//from   w  w w .  j  a  v  a  2  s.  co  m
  $Id$
    
  Copyright (C) 2003-2013 Virginia Tech.
  All rights reserved.
    
  SEE LICENSE FOR MORE INFORMATION
    
  Author:  Middleware Services
  Email:   middleware@vt.edu
  Version: $Revision$
  Updated: $Date$
*/

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
    /** Buffer size for stream reads. */
    private static final int BUFFER_SIZE = 1024;

    /**
     * Reads all data from a stream of unknown length.
     *
     * @param  in  Input stream to read.
     *
     * @return  Entire contents of stream.
     *
     * @throws  IOException  On read errors.
     */
    public static byte[] read(final InputStream in) throws IOException {
        final ByteArrayOutputStream out;
        try {
            out = new ByteArrayOutputStream();

            final byte[] buffer = new byte[BUFFER_SIZE];
            int count;
            while ((count = in.read(buffer)) > -1) {
                out.write(buffer, 0, count);
            }
        } finally {
            in.close();
        }
        return out.toByteArray();
    }

    /**
     * Reads all data from the given file channel. The channel is closed upon
     * completion.
     *
     * @param  channel  File channel to read.
     *
     * @return  Entire contents of channel.
     *
     * @throws  IOException  On read errors.
     */
    public static byte[] read(final FileChannel channel) throws IOException {
        final ByteBuffer buffer;
        try {
            buffer = ByteBuffer.allocateDirect((int) channel.size());
            channel.read(buffer);
        } finally {
            channel.close();
        }

        final byte[] result = new byte[buffer.flip().limit()];
        buffer.get(result);
        return result;
    }
}

Related

  1. read(File file)
  2. read(File file)
  3. read(File file, long offset, int length)
  4. read(File from)
  5. read(final File source)
  6. read(final Reader input, final char[] buffer, final int offset, final int length)
  7. read(InputStream stream)
  8. read(Path file)
  9. read(Path file, int pos, int length)