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