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      @Override public int read() throws IOException {
052        int result = in.read();
053        if (result != -1) {
054          count++;
055        }
056        return result;
057      }
058    
059      @Override public int read(byte[] b, int off, int len) throws IOException {
060        int result = in.read(b, off, len);
061        if (result != -1) {
062          count += result;
063        }
064        return result;
065      }
066    
067      @Override public long skip(long n) throws IOException {
068        long result = in.skip(n);
069        count += result;
070        return result;
071      }
072    
073      @Override public void mark(int readlimit) {
074        in.mark(readlimit);
075        mark = count;
076        // it's okay to mark even if mark isn't supported, as reset won't work
077      }
078    
079      @Override public void reset() throws IOException {
080        if (!in.markSupported()) {
081          throw new IOException("Mark not supported");
082        }
083        if (mark == -1) {
084          throw new IOException("Mark not set");
085        }
086    
087        in.reset();
088        count = mark;
089      }
090    }