    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.io;
    018
    019import static org.apache.commons.io.IOUtils.EOF;
    020
    021import java.io.ByteArrayInputStream;
    022import java.io.IOException;
    023import java.io.InputStream;
    024import java.io.InputStreamReader;
    025import java.io.OutputStream;
    026import java.io.OutputStreamWriter;
    027import java.io.Reader;
    028import java.io.StringReader;
    029import java.io.Writer;
    030import java.nio.charset.Charset;
    031
    032/**
    033 * This class provides static utility methods for buffered
    034 * copying between sources ({@link InputStream}, {@link Reader},
    035 * {@link String} and {@code byte[]}) and destinations
    036 * ({@link OutputStream}, {@link Writer}, {@link String} and
    037 * {@code byte[]}).
    038 * <p>
    039 * Unless otherwise noted, these {@code copy} methods do <em>not</em>
    040 * flush or close the streams. Often doing so would require making non-portable
    041 * assumptions about the streams' origin and further use. This means that both
    042 * streams' {@code close()} methods must be called after copying. if one
    043 * omits this step, then the stream resources (sockets, file descriptors) are
    044 * released when the associated Stream is garbage-collected. It is not a good
    045 * idea to rely on this mechanism. For a good overview of the distinction
    046 * between "memory management" and "resource management", see
    047 * <a href="http://www.unixreview.com/articles/1998/9804/9804ja/ja.htm">this
    048 * UnixReview article</a>.
    049 * <p>
    050 * For byte-to-char methods, a {@code copy} variant allows the encoding
    051 * to be selected (otherwise the platform default is used). We would like to
    052 * encourage you to always specify the encoding because relying on the platform
    053 * default can lead to unexpected results.
    054 * <p>
    055 * We don't provide special variants for the {@code copy} methods that
    056 * let you specify the buffer size because in modern VMs the impact on speed
    057 * seems to be minimal. We're using a default buffer size of 4 KB.
    058 * <p>
    059 * The {@code copy} methods use an internal buffer when copying. It is
    060 * therefore advisable <em>not</em> to deliberately wrap the stream arguments
    061 * to the {@code copy} methods in {@code Buffered*} streams. For
    062 * example, don't do the following:
    063 * <pre>
    064 *  copy( new BufferedInputStream( in ), new BufferedOutputStream( out ) );
    065 *  </pre>
    066 * The rationale is as follows:
    067 * <p>
    068 * Imagine that an InputStream's read() is a very expensive operation, which
    069 * would usually suggest wrapping in a BufferedInputStream. The
    070 * BufferedInputStream works by issuing infrequent
    071 * {@link java.io.InputStream#read(byte[] b, int off, int len)} requests on the
    072 * underlying InputStream, to fill an internal buffer, from which further
    073 * {@code read} requests can inexpensively get their data (until the buffer
    074 * runs out).
    075 * <p>
    076 * However, the {@code copy} methods do the same thing, keeping an
    077 * internal buffer, populated by
    078 * {@link InputStream#read(byte[] b, int off, int len)} requests. Having two
    079 * buffers (or three if the destination stream is also buffered) is pointless,
    080 * and the unnecessary buffer management hurts performance slightly (about 3%,
    081 * according to some simple experiments).
    082 * <p>
    083 * Behold, intrepid explorers; a map of this class:
    084 * <pre>
    085 *       Method      Input               Output          Dependency
    086 *       ------      -----               ------          -------
    087 * 1     copy        InputStream         OutputStream    (primitive)
    088 * 2     copy        Reader              Writer          (primitive)
    089 *
    090 * 3     copy        InputStream         Writer          2
    091 *
    092 * 4     copy        Reader              OutputStream    2
    093 *
    094 * 5     copy        String              OutputStream    2
    095 * 6     copy        String              Writer          (trivial)
    096 *
    097 * 7     copy        byte[]              Writer          3
    098 * 8     copy        byte[]              OutputStream    (trivial)
    099 * </pre>
    100 * <p>
    101 * Note that only the first two methods shuffle bytes; the rest use these
    102 * two, or (if possible) copy using native Java copy methods. As there are
    103 * method variants to specify the encoding, each row may
    104 * correspond to up to 2 methods.
    105 * <p>
    106 * Origin of code: Excalibur.
    107 *
    108 * @deprecated Use IOUtils. Will be removed in 3.0.
    109 *  Methods renamed to IOUtils.write() or IOUtils.copy().
    110 *  Null handling behavior changed in IOUtils (null data does not
    111 *  throw NullPointerException).
    112 */
    113@Deprecated
    114public class CopyUtils {
    115
    116    /**
    117     * Copies bytes from a {@code byte[]} to an {@link OutputStream}.
    118     * @param input the byte array to read from
    119     * @param output the {@link OutputStream} to write to
    120     * @throws IOException In case of an I/O problem
    121     */
    122    public static void copy(final byte[] input, final OutputStream output) throws IOException {
    123        output.write(input);
    124    }
    125
    126    /**
    127     * Copies and convert bytes from a {@code byte[]} to chars on a
    128     * {@link Writer}.
    129     * The platform's default encoding is used for the byte-to-char conversion.
    130     * @param input the byte array to read from
    131     * @param output the {@link Writer} to write to
    132     * @throws IOException In case of an I/O problem
    133     * @deprecated 2.5 use {@link #copy(byte[], Writer, String)} instead
    134     */
    135    @Deprecated
    136    public static void copy(final byte[] input, final Writer output) throws IOException {
    137        final ByteArrayInputStream inputStream = new ByteArrayInputStream(input);
    138        copy(inputStream, output);
    139    }
    140
    141    /**
    142     * Copies and convert bytes from a {@code byte[]} to chars on a
    143     * {@link Writer}, using the specified encoding.
    144     * @param input the byte array to read from
    145     * @param output the {@link Writer} to write to
    146     * @param encoding The name of a supported character encoding. See the
    147     * <a href="http://www.iana.org/assignments/character-sets">IANA
    148     * Charset Registry</a> for a list of valid encoding types.
    149     * @throws IOException In case of an I/O problem
    150     */
    151    public static void copy(final byte[] input, final Writer output, final String encoding) throws IOException {
    152        final ByteArrayInputStream inputStream = new ByteArrayInputStream(input);
    153        copy(inputStream, output, encoding);
    154    }
    155
    156    /**
    157     * Copies bytes from an {@link InputStream} to an
    158     * {@link OutputStream}.
    159     * @param input the {@link InputStream} to read from
    160     * @param output the {@link OutputStream} to write to
    161     * @return the number of bytes copied
    162     * @throws IOException In case of an I/O problem
    163     */
    164    public static int copy(final InputStream input, final OutputStream output) throws IOException {
    165        final byte[] buffer = IOUtils.byteArray();
    166        int count = 0;
    167        int n;
    168        while (EOF != (n = input.read(buffer))) {
    169            output.write(buffer, 0, n);
    170            count += n;
    171        }
    172        return count;
    173    }
    174
    175    /**
    176     * Copies and convert bytes from an {@link InputStream} to chars on a
    177     * {@link Writer}.
    178     * The platform's default encoding is used for the byte-to-char conversion.
    179     * @param input the {@link InputStream} to read from
    180     * @param output the {@link Writer} to write to
    181     * @throws IOException In case of an I/O problem
    182     * @deprecated 2.5 use {@link #copy(InputStream, Writer, String)} instead
    183     */
    184    @Deprecated
    185    public static void copy(
    186            final InputStream input,
    187            final Writer output)
    188                throws IOException {
    189        // make explicit the dependency on the default encoding
    190        final InputStreamReader in = new InputStreamReader(input, Charset.defaultCharset());
    191        copy(in, output);
    192    }
    193
    194    /**
    195     * Copies and convert bytes from an {@link InputStream} to chars on a
    196     * {@link Writer}, using the specified encoding.
    197     * @param input the {@link InputStream} to read from
    198     * @param output the {@link Writer} to write to
    199     * @param encoding The name of a supported character encoding. See the
    200     * <a href="http://www.iana.org/assignments/character-sets">IANA
    201     * Charset Registry</a> for a list of valid encoding types.
    202     * @throws IOException In case of an I/O problem
    203     */
    204    public static void copy(
    205            final InputStream input,
    206            final Writer output,
    207            final String encoding)
    208                throws IOException {
    209        final InputStreamReader in = new InputStreamReader(input, encoding);
    210        copy(in, output);
    211    }
    212
    213    /**
    214     * Serialize chars from a {@link Reader} to bytes on an
    215     * {@link OutputStream}, and flush the {@link OutputStream}.
    216     * Uses the default platform encoding.
    217     * @param input the {@link Reader} to read from
    218     * @param output the {@link OutputStream} to write to
    219     * @throws IOException In case of an I/O problem
    220     * @deprecated 2.5 use {@link #copy(Reader, OutputStream, String)} instead
    221     */
    222    @Deprecated
    223    public static void copy(
    224            final Reader input,
    225            final OutputStream output)
    226                throws IOException {
    227        // make explicit the dependency on the default encoding
    228        final OutputStreamWriter out = new OutputStreamWriter(output, Charset.defaultCharset());
    229        copy(input, out);
    230        // XXX Unless anyone is planning on rewriting OutputStreamWriter, we
    231        // have to flush here.
    232        out.flush();
    233    }
    234
    235    /**
    236     * Serialize chars from a {@link Reader} to bytes on an
    237     * {@link OutputStream}, and flush the {@link OutputStream}.
    238     * @param input the {@link Reader} to read from
    239     * @param output the {@link OutputStream} to write to
    240     * @param encoding The name of a supported character encoding. See the
    241     * <a href="http://www.iana.org/assignments/character-sets">IANA
    242     * Charset Registry</a> for a list of valid encoding types.
    243     * @throws IOException In case of an I/O problem
    244     * @since 2.5
    245     */
    246    public static void copy(
    247            final Reader input,
    248            final OutputStream output,
    249            final String encoding)
    250                throws IOException {
    251        final OutputStreamWriter out = new OutputStreamWriter(output, encoding);
    252        copy(input, out);
    253        // XXX Unless anyone is planning on rewriting OutputStreamWriter, we
    254        // have to flush here.
    255        out.flush();
    256    }
    257
    258    /**
    259     * Copies chars from a {@link Reader} to a {@link Writer}.
    260     * @param input the {@link Reader} to read from
    261     * @param output the {@link Writer} to write to
    262     * @return the number of characters copied
    263     * @throws IOException In case of an I/O problem
    264     */
    265    public static int copy(
    266            final Reader input,
    267            final Writer output)
    268                throws IOException {
    269        final char[] buffer = IOUtils.getScratchCharArray();
    270        int count = 0;
    271        int n;
    272        while (EOF != (n = input.read(buffer))) {
    273            output.write(buffer, 0, n);
    274            count += n;
    275        }
    276        return count;
    277    }
    278
    279    /**
    280     * Serialize chars from a {@link String} to bytes on an
    281     * {@link OutputStream}, and
    282     * flush the {@link OutputStream}.
    283     * Uses the platform default encoding.
    284     * @param input the {@link String} to read from
    285     * @param output the {@link OutputStream} to write to
    286     * @throws IOException In case of an I/O problem
    287     * @deprecated 2.5 use {@link #copy(String, OutputStream, String)} instead
    288     */
    289    @Deprecated
    290    public static void copy(
    291            final String input,
    292            final OutputStream output)
    293                throws IOException {
    294        final StringReader in = new StringReader(input);
    295        // make explicit the dependency on the default encoding
    296        final OutputStreamWriter out = new OutputStreamWriter(output, Charset.defaultCharset());
    297        copy(in, out);
    298        // XXX Unless anyone is planning on rewriting OutputStreamWriter, we
    299        // have to flush here.
    300        out.flush();
    301    }
    302
    303    /**
    304     * Serialize chars from a {@link String} to bytes on an
    305     * {@link OutputStream}, and
    306     * flush the {@link OutputStream}.
    307     * @param input the {@link String} to read from
    308     * @param output the {@link OutputStream} to write to
    309     * @param encoding The name of a supported character encoding. See the
    310     * <a href="http://www.iana.org/assignments/character-sets">IANA
    311     * Charset Registry</a> for a list of valid encoding types.
    312     * @throws IOException In case of an I/O problem
    313     * @since 2.5
    314     */
    315    public static void copy(
    316            final String input,
    317            final OutputStream output,
    318            final String encoding)
    319                throws IOException {
    320        final StringReader in = new StringReader(input);
    321        final OutputStreamWriter out = new OutputStreamWriter(output, encoding);
    322        copy(in, out);
    323        // XXX Unless anyone is planning on rewriting OutputStreamWriter, we
    324        // have to flush here.
    325        out.flush();
    326    }
    327
    328    /**
    329     * Copies chars from a {@link String} to a {@link Writer}.
    330     * @param input the {@link String} to read from
    331     * @param output the {@link Writer} to write to
    332     * @throws IOException In case of an I/O problem
    333     */
    334    public static void copy(final String input, final Writer output)
    335                throws IOException {
    336        output.write(input);
    337    }
    338
    339    /**
    340     * Instances should NOT be constructed in standard programming.
    341     */
    342    public CopyUtils() { }
    343
    344}