Java File Read via ByteBuffer nioCopy(ReadableByteChannel input, WritableByteChannel output)

Here you can find the source of nioCopy(ReadableByteChannel input, WritableByteChannel output)

Description

nio Copy

License

Apache License

Declaration

public static final void nioCopy(ReadableByteChannel input, WritableByteChannel output) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

public class Main {
    private static final int DEFAULT_BUFFER_SIZE = 8192;

    public static final void nioCopy(InputStream input, OutputStream output) throws IOException {
        nioCopy(Channels.newChannel(input), Channels.newChannel(output));
    }//from   w w w .ja va 2  s .  c  om

    public static final void nioCopy(ReadableByteChannel input, WritableByteChannel output) throws IOException {
        try {
            ByteBuffer buffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE);
            while (input.read(buffer) != -1) {
                //Flip buffer
                buffer.flip();
                //Write to destination
                output.write(buffer);
                //Compact
                buffer.compact();
            }

            //In case we have remainder
            buffer.flip();
            while (buffer.hasRemaining()) {
                //Write to output
                output.write(buffer);
            }
        } finally {
            if (input != null) {
                input.close();
                input = null;
            }

            if (output != null) {
                output.close();
                output = null;
            }
        }
    }
}

Related

  1. count(final ReadableByteChannel src)
  2. getReadBuffer(File file)
  3. getStringContents(ReadableByteChannel channel)
  4. largeFileReader(String filename)
  5. mapReadWrite(File file)
  6. openReadOnly(Path path, int offset, int length)
  7. read(DataInput in, int length)
  8. read(File file)
  9. read(File file)