Java File Read via ByteBuffer copy(final ReadableByteChannel src, final WritableByteChannel dest)

Here you can find the source of copy(final ReadableByteChannel src, final WritableByteChannel dest)

Description

copy

License

Open Source License

Declaration

public static void copy(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

public class Main {
    public static void copy(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException {
        final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
        while (src.read(buffer) != -1) {
            buffer.flip();/*from ww  w .  ja v a 2s.c  o m*/
            dest.write(buffer);
            buffer.compact();
        }
        buffer.flip();
        while (buffer.hasRemaining()) {
            dest.write(buffer);
        }
    }

    public static void copy(File source, File dest) throws IOException {
        try (InputStream is = new FileInputStream(source);
                FileOutputStream destination = new FileOutputStream(dest);) {
            copy(Channels.newChannel(is), destination.getChannel());
        }
    }
}

Related

  1. blockingRead(SocketChannel so, long timeout, int bytes)
  2. channelCopy(@Nonnull @WillNotClose final ReadableByteChannel aSrc, @Nonnull @WillNotClose final WritableByteChannel aDest)
  3. channelCopy2(ReadableByteChannel src, WritableByteChannel dest)
  4. ClientReadWithBlock(SocketChannel sc)
  5. ClientReadWithWait(SocketChannel sc)
  6. copy(final ReadableByteChannel srcChannel, final WritableByteChannel destChannel)
  7. copyChannel(int bufferSize, ReadableByteChannel source, WritableByteChannel destination)
  8. copyStream(BufferedReader reader, BufferedWriter writer)
  9. count(final ReadableByteChannel src)