Java FileChannel Copy copyStream(InputStream in, long length, File out)

Here you can find the source of copyStream(InputStream in, long length, File out)

Description

copies the contens of a stream to a file

License

Open Source License

Declaration

public static long copyStream(InputStream in, long length, File out) throws IOException 

Method Source Code


//package com.java2s;
/*//from w  ww  .j  a  va2s.c o m
 * This file is part of the Jose Project
 * see http://jose-chess.sourceforge.net/
 * (c) 2002-2006 Peter Sch?fer
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 */

import java.io.*;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

public class Main {
    /**
    * copies the contens of a stream to a file
    */
    public static long copyStream(InputStream in, long length, File out) throws IOException {
        FileOutputStream stream = new FileOutputStream(out);

        ReadableByteChannel cin = Channels.newChannel(in);
        long result = copyChannel(cin, length, stream.getChannel());

        stream.close();
        return result;
    }

    public static long copyChannel(FileChannel in, long length, WritableByteChannel out) throws IOException {
        if (length < 0L || length >= Integer.MAX_VALUE)
            return in.transferTo(0L, length, out);

        long result = 0L;
        while (result < length)
            result += in.transferTo(result, length - result, out);
        return result;
    }

    public static long copyChannel(ReadableByteChannel in, long length, FileChannel out) throws IOException {
        if (length < 0L || length >= Integer.MAX_VALUE)
            return out.transferFrom(in, 0L, length);

        long result = 0L;
        while (result < length)
            result += out.transferFrom(in, result, length - result);
        return result;
    }
}

Related

  1. copyFromZip(ZipFile zipFile, String locationInBundle, File destination)
  2. copyInternal(FileInputStream in, FileOutputStream out)
  3. copyLarge(FileInputStream in, FileOutputStream out)
  4. copyNio(final File source_file, final File destination_file)
  5. copyRec(File src, File dst)
  6. copyStreamToFile(InputStream inStream, File file)
  7. copyThrowsOnException(final File source, final File destination)
  8. copyTo(File srcFile, File destFile)
  9. copyToFolderAs(File fromFile, File folder, String asName)