Here you can find the source of copyTo(ReadableByteChannel from, WritableByteChannel to)
Parameter | Description |
---|---|
from | the readable channel to read from |
to | the writable channel to write to |
Parameter | Description |
---|---|
IOException | if an I/O error occurs |
public static long copyTo(ReadableByteChannel from, WritableByteChannel to) throws IOException
//package com.java2s; //License from project: Open Source License import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Channel; import java.nio.channels.ReadableByteChannel; import java.nio.channels.Selector; import java.nio.channels.WritableByteChannel; public class Main { private static final int BUF_SIZE = 0x1000; /**/*w ww . j a v a 2 s . co m*/ * Copies all bytes from the readable channel to the writable channel. * Does not close or flush either channel. * * @param from the readable channel to read from * @param to the writable channel to write to * @return the number of bytes copied * @throws IOException if an I/O error occurs */ public static long copyTo(ReadableByteChannel from, WritableByteChannel to) throws IOException { return copyTo(from, to, false); } /** * Copies all bytes from the readable channel to the writable channel. * Will close both channels when done if specified. * * @param from the readable channel to read from * @param to the writable channel to write to * @param close - Close the channels when finished. * @return the number of bytes copied * @throws IOException if an I/O error occurs */ public static long copyTo(ReadableByteChannel from, WritableByteChannel to, boolean close) throws IOException { ByteBuffer buf = ByteBuffer.allocate(BUF_SIZE); long total = 0; try { while (from.read(buf) != -1) { buf.flip(); while (buf.hasRemaining()) { total += to.write(buf); } buf.clear(); } } finally { if (close) { close(from); close(to); } } return total; } /** * Shutdown the given channel. * * @param channel The channel to close. * @return True if successful, false if an error occurred */ public static boolean close(Channel channel) { try { channel.close(); return true; } catch (Exception ex) { return false; } } /** * Shutdown the given selector. * * @param selector The selector to close. * @return True if successful, false if an error occurred */ public static boolean close(Selector selector) { try { selector.close(); return true; } catch (Exception ex) { return false; } } }