Java InputStream Copy nio copy(InputStream input, OutputStream output)

Here you can find the source of copy(InputStream input, OutputStream output)

Description

copy

License

Apache License

Declaration

public static void copy(InputStream input, OutputStream output) 

Method Source Code

//package com.java2s;
/**//from  w  ww.  j a  va 2s .c om
 * Copyright 2016 Pascal
 *
 * 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.File;

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

import java.io.OutputStream;
import java.io.OutputStreamWriter;

import java.io.Writer;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class Main {
    private static final Charset CHARSET = StandardCharsets.UTF_8;
    static final int BUFFER_SIZE = 4096;

    public static void copy(InputStream input, OutputStream output) {
        byte[] buf = new byte[BUFFER_SIZE];
        try {
            int len;
            while ((len = input.read(buf)) != -1) {
                output.write(buf, 0, len);
            }
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    public static void write(File file, String content) {
        write(file, CHARSET, content);
    }

    public static void write(File file, Charset charset, String content) {
        try (Writer writer = createWriter(file, charset)) {
            writer.write(content);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }

    public static Writer createWriter(File file) throws FileNotFoundException {
        return createWriter(file, CHARSET);
    }

    public static Writer createWriter(File file, Charset charset) throws FileNotFoundException {
        return new OutputStreamWriter(new FileOutputStream(file), charset);
    }
}

Related

  1. copy(InputStream in, OutputStream out)
  2. copy(InputStream in, OutputStream out, boolean closeInput, boolean closeOutput)
  3. copy(InputStream input, OutputStream output)
  4. copy(InputStream input, OutputStream output)
  5. copy(InputStream input, OutputStream output)
  6. copy(InputStream src, File dst)
  7. copy(InputStream stream, File file)
  8. copyStream(final InputStream aInStream, final OutputStream aOutStream)
  9. copyStream(final InputStream in)