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

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

Description

copy

License

Open Source License

Declaration

public static void copy(InputStream input, OutputStream output) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.channels.FileChannel;

public class Main {
    public static void copy(File input, File output) throws URISyntaxException, IOException {
        copy(new URI("file://" + input.getAbsolutePath()), output);
    }//from  w  w  w  .  jav  a 2s .c o m

    public static void copy(URI input, File output) throws IOException {
        try {
            InputStream in = null;
            try {
                File f = new File(input);
                if (f.exists())
                    in = new FileInputStream(f);
            } catch (Exception notAFile) {
            }

            File out = output;

            if (in == null) {
                in = input.toURL().openStream();
            }

            copy(in, new FileOutputStream(out));
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            throw new IOException("Cannot copy to " + output + " " + e);
        }
    }

    public static void copy(InputStream input, OutputStream output) throws IOException {
        // if both are file streams, use channel IO
        if ((output instanceof FileOutputStream) && (input instanceof FileInputStream)) {
            try {
                FileChannel target = ((FileOutputStream) output).getChannel();
                FileChannel source = ((FileInputStream) input).getChannel();

                source.transferTo(0, Integer.MAX_VALUE, target);

                source.close();
                target.close();

                return;
            } catch (Exception e) {
            }
        }

        byte[] buf = new byte[8192];
        while (true) {
            int length = input.read(buf);
            if (length < 0)
                break;
            output.write(buf, 0, length);
        }

        try {
            input.close();
        } catch (IOException ignore) {
        }
        try {
            output.close();
        } catch (IOException ignore) {
        }
    }
}

Related

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