Java InputStream Copy to File copyStream(final InputStream in, final File dest)

Here you can find the source of copyStream(final InputStream in, final File dest)

Description

Copies the content of the InputStream in to the File dest.

License

Open Source License

Parameter

Parameter Description
in Stream to copy.
dest File to put content of stream into.

Exception

Parameter Description
IOException Is thrown if operations on target file fail.

Declaration

public static void copyStream(final InputStream in, final File dest)
        throws IOException 

Method Source Code

//package com.java2s;
/**/*ww w .  j  ava  2 s  .  c  om*/
 * Copyright (c) 2011, Marc R?ttig, Stephan Aiche.
 *
 * This file is part of GenericKnimeNodes.
 * 
 * GenericKnimeNodes is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.io.BufferedInputStream;

import java.io.File;
import java.io.FileOutputStream;

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

public class Main {
    /**
     * Size of the buffer when copying streams to files.
     */
    private static final int BUFFER_SIZE = 2048;

    /**
     * Copies the content of the {@link InputStream} in to the {@link File}
     * dest.
     * 
     * @param in
     *            Stream to copy.
     * @param dest
     *            File to put content of stream into.
     * @throws IOException
     *             Is thrown if operations on target file fail.
     */
    public static void copyStream(final InputStream in, final File dest)
            throws IOException {
        FileOutputStream out = new FileOutputStream(dest);
        BufferedInputStream bin = new BufferedInputStream(in);

        try {
            byte[] buffer = new byte[BUFFER_SIZE];
            int len;
            while ((len = bin.read(buffer, 0, 2048)) != -1) {
                out.write(buffer, 0, len);
            }
            out.close();
            bin.close();
        } catch (IOException ex) {
            // try to close the streams
            out.close();
            bin.close();

            // rethrow exception
            throw ex;
        }

    }
}

Related

  1. copyStream(final InputStream is, final File destinationFile)
  2. copyStream(InputStream copyFrom, File copyTo)
  3. copyStream(InputStream in, File dest)
  4. copyStream(InputStream in, File dest)