Search This Blog

Java: copy from InputStream to OutputStream

The following utitlity class: StreamUtil.java contains function to copy streams.
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StreamUtil {

    public static final int BUFFER_SIZE = 8192;

    public static long copy(final InputStream input, final OutputStream output)
            throws IOException {

        return copy(input, output, BUFFER_SIZE);

    }

    public static long copy(final InputStream input, final OutputStream output,
            int bufferSize) throws IOException {

        final byte[] buffer = new byte[bufferSize];
        int n = 0;
        long count = 0;
        while ((n = input.read(buffer)) > 0) {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }
}



Usage:


BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File("/tmp/input.txt")));
BufferedOutputStream out = new BuefferedOutputStream(new FileOutputStream(new File("/tmp/output.txt")));
try {
    StreamUtil.copy(in, out);
} catch(Throwable e) {
    e.printStactTrace();
} finally {
    out.close();
    in.close();
}

No comments:

Post a Comment