001    /*
002     * Copyright (C) 2007 The Guava Authors
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package com.google.common.io;
018    
019    import com.google.common.annotations.Beta;
020    
021    import java.io.FilterInputStream;
022    import java.io.IOException;
023    import java.io.InputStream;
024    
025    /**
026     * An {@link InputStream} that counts the number of bytes read.
027     *
028     * @author Chris Nokleberg
029     * @since 1.0
030     */
031    @Beta
032    public final class CountingInputStream extends FilterInputStream {
033    
034      private long count;
035      private long mark = -1;
036    
037      /**
038       * Wraps another input stream, counting the number of bytes read.
039       *
040       * @param in the input stream to be wrapped
041       */
042      public CountingInputStream(InputStream in) {
043        super(in);
044      }
045    
046      /** Returns the number of bytes read. */
047      public long getCount() {
048        return count;
049      }
050    
051      
052      @Override
053      public int read() throws IOException {
054        int result = in.read();
055        if (result != -1) {
056          count++;
057        }
058        return result;
059      }
060    
061      
062      @Override
063      public int read(byte[] b, int off, int len) throws IOException {
064        int result = in.read(b, off, len);
065        if (result != -1) {
066          count += result;
067        }
068        return result;
069      }
070    
071      
072      @Override
073      public long skip(long n) throws IOException {
074        long result = in.skip(n);
075        count += result;
076        return result;
077      }
078    
079      
080      @Override
081      public synchronized void mark(int readlimit) {
082        in.mark(readlimit);
083        mark = count;
084        // it's okay to mark even if mark isn't supported, as reset won't work
085      }
086    
087      
088      @Override
089      public synchronized void reset() throws IOException {
090        if (!in.markSupported()) {
091          throw new IOException("Mark not supported");
092        }
093        if (mark == -1) {
094          throw new IOException("Mark not set");
095        }
096    
097        in.reset();
098        count = mark;
099      }
100    }