You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@commons.apache.org by "Sebb (JIRA)" <ji...@apache.org> on 2013/05/16 16:33:34 UTC

[jira] [Updated] (IO-339) MaxBytesInputStream to limit size of bytes read

     [ https://issues.apache.org/jira/browse/IO-339?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel ]

Sebb updated IO-339:
--------------------

    Fix Version/s: 2.5
    
> MaxBytesInputStream to limit size of bytes read
> -----------------------------------------------
>
>                 Key: IO-339
>                 URL: https://issues.apache.org/jira/browse/IO-339
>             Project: Commons IO
>          Issue Type: Improvement
>          Components: Streams/Writers
>    Affects Versions: 2.4
>            Reporter: Ken Weiner
>            Priority: Minor
>             Fix For: 2.5
>
>
> I wrote an input stream that stops when it reaches a configured size in bytes.  I found it useful for applications that download web pages and images, but want to enforce a max size to avoid memory problems for extremely large pages/images.
> I was thinking that this class is generic and useful enough to include in the commons-io distribution.  Please consider it, and if it isn't appropriate for inclusion here, please recommend a better place to open source and share it.
> {code}
> package org.apache.commons.io.input;
> import java.io.IOException;
> import java.io.InputStream;
> /**
>  * An input stream that will end when the amount of bytes read reaches
>  * the configured amount of maxBytes.
>  * This is useful for preventing OutOfMemoryExceptions when downloading
>  * very large files in cases where getting partial content is acceptable.
>  * @author Ken Weiner
>  */
> public class MaxBytesInputStream extends CountingInputStream {
>     private long maxBytes;
>     public MaxBytesInputStream(InputStream is, long maxBytes) {
>         super(is);
>         this.maxBytes = maxBytes;
>     }
>     @Override
>     protected void afterRead(int n) {
>         super.afterRead((int) Math.min(n, this.maxBytes - getByteCount()));
>     }
>     @Override
>     public int read() throws IOException {
>         if (getByteCount() < this.maxBytes) {
>             return super.read();
>         }
>         return -1;
>     }
>     @Override
>     public int read(byte[] b) throws IOException {
>         if (getByteCount() < this.maxBytes) {
>             return super.read(b);
>         }
>         return -1;
>     }
>     @Override
>     public int read(byte[] b, int off, int len) throws IOException {
>         if (getByteCount() < this.maxBytes) {
>             return super.read(b, off, len);
>         }
>         return -1;
>     }
> }
> {code}

--
This message is automatically generated by JIRA.
If you think it was sent incorrectly, please contact your JIRA administrators
For more information on JIRA, see: http://www.atlassian.com/software/jira