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 */
019package org.apache.commons.compress.utils;
020
021import java.io.FilterOutputStream;
022import java.io.IOException;
023import java.io.OutputStream;
024
025/**
026 * Stream that tracks the number of bytes read.
027 * @since 1.3
028 * @NotThreadSafe
029 */
030public class CountingOutputStream extends FilterOutputStream {
031    private long bytesWritten;
032
033    public CountingOutputStream(final OutputStream out) {
034        super(out);
035    }
036
037    /**
038     * Increments the counter of already written bytes.
039     * Doesn't increment if the EOF has been hit (written == -1)
040     *
041     * @param written the number of bytes written
042     */
043    protected void count(final long written) {
044        if (written != -1) {
045            bytesWritten += written;
046        }
047    }
048    /**
049     * Returns the current number of bytes written to this stream.
050     * @return the number of written bytes
051     */
052    public long getBytesWritten() {
053        return bytesWritten;
054    }
055    @Override
056    public void write(final byte[] b) throws IOException {
057        write(b, 0, b.length);
058    }
059
060    @Override
061    public void write(final byte[] b, final int off, final int len) throws IOException {
062        out.write(b, off, len);
063        count(len);
064    }
065
066    @Override
067    public void write(final int b) throws IOException {
068        out.write(b);
069        count(1);
070    }
071}