Here you can find the source of fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest)
ReadableByteChannel
into a WritableByteChannel
byte channel.
Parameter | Description |
---|---|
src | the <code>ReadableByteChannel</code> to read from |
dest | the <code>ReadableByteChannel</code> to write into |
Parameter | Description |
---|
private static void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest)
//package com.java2s; /*//from w w w .j ava 2 s.c o m * Copyright (C) 2010 Google Code. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; public class Main { /** * The default buffer size to use for * {@link #copyLarge(InputStream, OutputStream)} * and * {@link #copyLarge(Reader, Writer)} */ private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; /** * Copies a <code>ReadableByteChannel</code> into a <code>WritableByteChannel</code> byte channel. Uses a <code>ByteBuffer</code> * to write to the channel. The buffer is drained before each write. * * @param src the <code>ReadableByteChannel</code> to read from * @param dest the <code>ReadableByteChannel</code> to write into * @throws <code>IOException</code> if there is an I/O error */ private static void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest) { final ByteBuffer buffer = ByteBuffer.allocateDirect(DEFAULT_BUFFER_SIZE); try { while (src.read(buffer) != -1) { //prepare the buffer to be drained. buffer.flip(); //write to the channel. may block. dest.write(buffer); //if partial transfer, shift remainder down. //if buffer is empty, same as compact buffer.compact(); } //EOF will leave buffer in fill state buffer.flip(); //make sure buffer is fully drained. while (buffer.hasRemaining()) { dest.write(buffer); } } catch (IOException e) { e.printStackTrace(); } } }