StreamCopier.java 1.23 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision$
 * $Date$
 *
6
 * Copyright (C) 2004 Jive Software. All rights reserved.
Matt Tucker's avatar
Matt Tucker committed
7
 *
8 9
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
Matt Tucker's avatar
Matt Tucker committed
10
 */
11

Matt Tucker's avatar
Matt Tucker committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
package org.jivesoftware.util;

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

/**
 * Fast way to copy data from one stream to another.
 * From ORA Java I/O by Elliotte Rusty Harold.
 *
 * @author Iain Shigeoka
 */
public class StreamCopier {
    /**
     * Copies data from an input stream to an output stream
     *
     * @param in  The stream to copy data from
     * @param out The stream to copy data to
     * @throws IOException if there's trouble during the copy
     */
    public static void copy(InputStream in, OutputStream out) throws IOException {
        // do not allow other threads to whack on in or out during copy
        synchronized (in) {
            synchronized (out) {
                byte[] buffer = new byte[256];
                while (true) {
                    int bytesRead = in.read(buffer);
                    if (bytesRead == -1) break;
                    out.write(buffer, 0, bytesRead);
                }
            }
        }
    }
}