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 * 017 */ 018package org.apache.commons.compress.utils; 019 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 InputStream { 029 private final InputStream in; 030 private long bytesRemaining; 031 032 /** 033 * Creates the stream that will at most read the given amount of 034 * bytes from the given stream. 035 * @param in the stream to read from 036 * @param size the maximum amount of bytes to read 037 */ 038 public BoundedInputStream(final InputStream in, final long size) { 039 this.in = in; 040 bytesRemaining = size; 041 } 042 043 @Override 044 public int read() throws IOException { 045 if (bytesRemaining > 0) { 046 --bytesRemaining; 047 return in.read(); 048 } else { 049 return -1; 050 } 051 } 052 053 @Override 054 public int read(byte[] b, int off, int len) throws IOException { 055 if (bytesRemaining == 0) { 056 return -1; 057 } 058 int bytesToRead = len; 059 if (bytesToRead > bytesRemaining) { 060 bytesToRead = (int) bytesRemaining; 061 } 062 final int bytesRead = in.read(b, off, bytesToRead); 063 if (bytesRead >= 0) { 064 bytesRemaining -= bytesRead; 065 } 066 return bytesRead; 067 } 068 069 @Override 070 public void close() { 071 // there isn't anything to close in this stream and the nested 072 // stream is controlled externally 073 } 074}