2013-02-04 62 views

回答

0

似乎有出的现成没办法。我最终编写了一个自己的“LimitedInputStream”实现。

LimitedInputStream:

public class LimitedInputStream extends InputStream { 
    public static InputStream create(ILimitedInputStreamPolicy policy, InputStream wrapped) { 
     return new LimitedInputStream(policy, wrapped); 
    } 

    public static InputStream create(Logger log, InputStream wrapped) { 
     final ILimitedInputStreamPolicy policy = BytesPerIntervalLimitedInputStreamPolicy.create(log); 
     return new LimitedInputStream(policy, wrapped); 
    } 

    private final ILimitedInputStreamPolicy policy; 
    private final InputStream wrapped; 

    private LimitedInputStream(ILimitedInputStreamPolicy policy, InputStream wrapped) { 
     this.policy = policy; 
     this.wrapped = wrapped; 
    } 

    @Override 
    public int available() throws IOException { 
     return wrapped.available(); 
    } 

    @Override 
    public void close() throws IOException { 
     wrapped.close(); 
    } 

    @Override 
    public boolean equals(Object obj) { 
     return wrapped.equals(obj); 
    } 

    @Override 
    public int hashCode() { 
     return wrapped.hashCode(); 
    } 

    @Override 
    public void mark(int readlimit) { 
     wrapped.mark(readlimit); 
    } 

    @Override 
    public boolean markSupported() { 
     return wrapped.markSupported(); 
    } 

    @Override 
    public int read() throws IOException { 
     policy.waitForBytesToRead(); 
     final int result = wrapped.read(); 
     policy.bytesRead(1); 
     return result; 
    } 

    @Override 
    public int read(byte[] b, int off, int len) throws IOException { 
     final long bytesLeft = policy.waitForBytesToRead(); 
     final int bytesToRead = Long.valueOf(Math.min(bytesLeft, len)).intValue(); 
     final int bytesRead = wrapped.read(b, off, bytesToRead); 
     policy.bytesRead(bytesRead); 
     return bytesRead; 
    } 

    @Override 
    public void reset() throws IOException { 
     wrapped.reset(); 
    } 

    @Override 
    public long skip(long n) throws IOException { 
     return wrapped.skip(n); 
    } 
} 

ILimitedInputStreamPolicy.java:

/** 
* Implementing class provide information about in which intervals how much data 
* may be read from a stream. 
*/ 
public interface ILimitedInputStreamPolicy { 
    /** 
    * Indicates that the given number of bytes have been read in any atomic 
    * action. 
    * 
    * @param numberOfBytes 
    *   The number of bytes read. 
    */ 
    public void bytesRead(int numberOfBytes); 

    /** 
    * Pauses the current thread until the implemented policy allows for the 
    * returned amount of bytes to read, 
    * 
    * @return The number of bytes allowed to read. 
    */ 
    public int waitForBytesToRead(); 
}