Home | History | Annotate | Download | only in io
      1 /*
      2  * Copyright (C) 2007 Google Inc.
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  * http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 package com.google.common.io;
     18 
     19 import java.io.FilterInputStream;
     20 import java.io.IOException;
     21 import java.io.InputStream;
     22 
     23 /**
     24  * An {@link InputStream} that counts the number of bytes read.
     25  *
     26  * @author Chris Nokleberg
     27  * @since 2009.09.15 <b>tentative</b>
     28  */
     29 public class CountingInputStream extends FilterInputStream {
     30 
     31   private long count;
     32   private long mark = -1;
     33 
     34   /**
     35    * Wraps another input stream, counting the number of bytes read.
     36    *
     37    * @param in the input stream to be wrapped
     38    */
     39   public CountingInputStream(InputStream in) {
     40     super(in);
     41   }
     42 
     43   /** Returns the number of bytes read. */
     44   public long getCount() {
     45     return count;
     46   }
     47 
     48   @Override public int read() throws IOException {
     49     int result = in.read();
     50     if (result != -1) {
     51       count++;
     52     }
     53     return result;
     54   }
     55 
     56   @Override public int read(byte[] b, int off, int len) throws IOException {
     57     int result = in.read(b, off, len);
     58     if (result != -1) {
     59       count += result;
     60     }
     61     return result;
     62   }
     63 
     64   @Override public long skip(long n) throws IOException {
     65     long result = in.skip(n);
     66     count += result;
     67     return result;
     68   }
     69 
     70   @Override public void mark(int readlimit) {
     71     in.mark(readlimit);
     72     mark = count;
     73     // it's okay to mark even if mark isn't supported, as reset won't work
     74   }
     75 
     76   @Override public void reset() throws IOException {
     77     if (!in.markSupported()) {
     78       throw new IOException("Mark not supported");
     79     }
     80     if (mark == -1) {
     81       throw new IOException("Mark not set");
     82     }
     83 
     84     in.reset();
     85     count = mark;
     86   }
     87 }
     88