Java File Read via ByteBuffer read(InputStream stream)

Here you can find the source of read(InputStream stream)

Description

read

License

Apache License

Declaration

public static ByteArrayOutputStream read(InputStream stream) throws IOException 

Method Source Code


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

import java.io.ByteArrayOutputStream;
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 {
    public static ByteArrayOutputStream read(InputStream stream) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        fastCopy(stream, baos);//from   w  w w . j a va  2  s .c o  m
        return baos;
    }

    public static void fastCopy(InputStream input, OutputStream output) throws IOException {
        ReadableByteChannel src = Channels.newChannel(input);
        WritableByteChannel dest = Channels.newChannel(output);
        ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
        while (src.read(buffer) != -1) {
            buffer.flip();
            dest.write(buffer);
            buffer.compact();
        }
        buffer.flip();
        while (buffer.hasRemaining()) {
            dest.write(buffer);
        }
        src.close();
        dest.close();
    }
}

Related

  1. read(File file, long offset, int length)
  2. read(File from)
  3. read(final File source)
  4. read(final FileChannel channel)
  5. read(final Reader input, final char[] buffer, final int offset, final int length)
  6. read(Path file)
  7. read(Path file, int pos, int length)
  8. read(Reader reader)
  9. read24BitInteger(byte[] threeBytes, ByteOrder order)