Java InputStream Copy to File copyStreamToFile(final File to, final InputStream from)

Here you can find the source of copyStreamToFile(final File to, final InputStream from)

Description

Copy the contents of a stream to the given file.

License

Apache License

Parameter

Parameter Description
to A file (which may not yet exist).
from The stream from which to copy (must be open).

Declaration

public static void copyStreamToFile(final File to, final InputStream from) throws IOException 

Method Source Code

//package com.java2s;
/*/*  ww w  .  j ava 2 s.  c o  m*/
 * Copyright (C) 2015 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.io.BufferedOutputStream;
import java.io.File;

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

public class Main {
    private static final int BUF_SIZE = 1024;

    /**
     * Copy the contents of a stream to the given file.
     * 
     * @param to
     *          A file (which may not yet exist).
     * @param from
     *          The stream from which to copy (must be open).
     */
    public static void copyStreamToFile(final File to, final InputStream from) throws IOException {
        if (!to.exists()) {
            to.createNewFile();
        }
        BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(to));

        copyStream(writer, from);

        writer.close();
    }

    /**
     * Copy one stream to another until the input stream has no more data.
     * 
     * @param to
     *          The open stream to write to.
     * @param from
     *          The open stream to read from.
     */
    public static void copyStream(final OutputStream to, final InputStream from) throws IOException {
        final byte[] buf = new byte[BUF_SIZE];
        int len = from.read(buf);
        while (len > 0) {
            to.write(buf, 0, len);
            len = from.read(buf);
        }
    }
}

Related

  1. copyStream(InputStream in, File dest)
  2. copyStream(InputStream in, File dest)
  3. copyStreamIntoFile(File outFile, InputStream is)
  4. copyStreamsToFile(String path, Map streamMap)
  5. copyStreamsToFolder(Iterator> streams, File folder)
  6. copyStreamToFile(InputStream from, File to)
  7. copyStreamToFile(InputStream in, File destination)
  8. copyStreamToFile(InputStream in, File out)
  9. copyStreamToFile(InputStream in, File target)