    001    /*
    002     * Licensed to the Apache Software Foundation (ASF) under one
    003     * or more contributor license agreements.  See the NOTICE file
    004     * distributed with this work for additional information
    005     * regarding copyright ownership.  The ASF licenses this file
    006     * to you under the Apache License, Version 2.0 (the
    007     * "License"); you may not use this file except in compliance
    008     * with the License.  You may obtain a copy of the License at
    009     *
    010     * http://www.apache.org/licenses/LICENSE-2.0
    011     *
    012     * Unless required by applicable law or agreed to in writing,
    013     * software distributed under the License is distributed on an
    014     * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    015     * KIND, either express or implied.  See the License for the
    016     * specific language governing permissions and limitations
    017     * under the License.
    018     */
    019    package org.apache.commons.compress.utils;
    020
    021    import java.io.FilterOutputStream;
    022    import java.io.IOException;
    023    import java.io.OutputStream;
    024
    025    /**
    026     * Stream that tracks the number of bytes read.
    027     * @since Apache Commons Compress 1.3
    028     * @NotThreadSafe
    029     */
    030    public class CountingOutputStream extends FilterOutputStream {
    031        private long bytesWritten = 0;
    032
    033        public CountingOutputStream(final OutputStream out) {
    034            super(out);
    035        }
    036
    037        @Override
    038        public void write(int b) throws IOException {
    039            out.write(b);
    040            count(1);
    041        }
    042        @Override
    043        public void write(byte[] b) throws IOException {
    044            write(b, 0, b.length);
    045        }
    046        @Override
    047        public void write(byte[] b, int off, int len) throws IOException {
    048            out.write(b, off, len);
    049            count(len);
    050        }
    051
    052        /**
    053         * Increments the counter of already written bytes.
    054         * Doesn't increment if the EOF has been hit (written == -1)
    055         *
    056         * @param written the number of bytes written
    057         */
    058        protected void count(long written) {
    059            if (written != -1) {
    060                bytesWritten += written;
    061            }
    062        }
    063
    064        /**
    065         * Returns the current number of bytes written to this stream.
    066         * @return the number of written bytes
    067         */
    068        public long getBytesWritten() {
    069            return bytesWritten;
    070        }
    071    }