001/* 002 * Copyright 2014 Konik.io 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 */ 016package io.konik.carriage.utils; 017 018import java.io.FilterInputStream; 019import java.io.IOException; 020import java.io.InputStream; 021 022/** 023 * 024 * Input Stream that also counting Byte Bytes. 025 */ 026public final class ByteCountingInputStream extends FilterInputStream { 027 private int byteCount; 028 private int mark = -1; 029 030 /** 031 * Instantiates a new byte counting input stream. 032 * @param in the in 033 */ 034 public ByteCountingInputStream(InputStream in) { 035 super(in); 036 } 037 038 /** 039 * Returns bytes read. 040 * 041 * @return the count 042 */ 043 public int getByteCount() { 044 return byteCount; 045 } 046 047 @Override 048 public int read() throws IOException { 049 int result = in.read(); 050 if (result != -1) { 051 byteCount++; 052 } 053 return result; 054 } 055 056 @Override 057 public int read(byte[] b, int off, int len) throws IOException { 058 int read = in.read(b, off, len); 059 if (read != -1) { 060 byteCount += read; 061 } 062 return read; 063 } 064 065 @Override 066 public long skip(long n) throws IOException { 067 long skip = in.skip(n); 068 byteCount += skip; 069 return skip; 070 } 071 072 @Override 073 public synchronized void mark(int readlimit) { 074 in.mark(readlimit); 075 mark = byteCount; 076 } 077 078 @Override 079 public synchronized void reset() throws IOException { 080 if (!in.markSupported()) { throw new IOException("Mark is not supported"); } 081 if (mark == -1) { throw new IOException("Mark not set"); } 082 in.reset(); 083 byteCount = mark; 084 } 085}