Here you can find the source of read(final FileChannel channel)
Parameter | Description |
---|---|
channel | File channel to read. |
Parameter | Description |
---|---|
IOException | On read errors. |
public static byte[] read(final FileChannel channel) throws IOException
//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; } }