001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.compress.utils; 018 019import java.io.FilterInputStream; 020import java.io.IOException; 021import java.io.InputStream; 022 023/** 024 * A stream that limits reading from a wrapped stream to a given number of bytes. 025 * @NotThreadSafe 026 * @since 1.6 027 */ 028public class BoundedInputStream extends FilterInputStream { 029 private long bytesRemaining; 030 031 /** 032 * Creates the stream that will at most read the given amount of 033 * bytes from the given stream. 034 * @param in the stream to read from 035 * @param size the maximum amount of bytes to read 036 */ 037 public BoundedInputStream(final InputStream in, final long size) { 038 super(in); 039 bytesRemaining = size; 040 } 041 042 @Override 043 public void close() { 044 // there isn't anything to close in this stream and the nested 045 // stream is controlled externally 046 } 047 048 /** 049 * @return bytes remaining to read 050 * @since 1.21 051 */ 052 public long getBytesRemaining() { 053 return bytesRemaining; 054 } 055 056 @Override 057 public int read() throws IOException { 058 if (bytesRemaining > 0) { 059 --bytesRemaining; 060 return in.read(); 061 } 062 return -1; 063 } 064 065 @Override 066 public int read(final byte[] b, final int off, final int len) throws IOException { 067 if (len == 0) { 068 return 0; 069 } 070 if (bytesRemaining == 0) { 071 return -1; 072 } 073 int bytesToRead = len; 074 if (bytesToRead > bytesRemaining) { 075 bytesToRead = (int) bytesRemaining; 076 } 077 final int bytesRead = in.read(b, off, bytesToRead); 078 if (bytesRead >= 0) { 079 bytesRemaining -= bytesRead; 080 } 081 return bytesRead; 082 } 083 084 /** 085 * @since 1.20 086 */ 087 @Override 088 public long skip(final long n) throws IOException { 089 final long bytesToSkip = Math.min(bytesRemaining, n); 090 final long bytesSkipped = in.skip(bytesToSkip); 091 bytesRemaining -= bytesSkipped; 092 093 return bytesSkipped; 094 } 095}