Parcourir la source

ByteLimitedInputStream now throws IOException if stream limit exceeded

tags/2.0.1
Jonathan Cobb il y a 4 ans
Parent
révision
825ce0905f
1 fichiers modifiés avec 23 ajouts et 6 suppressions
  1. +23
    -6
      src/main/java/org/cobbzilla/util/io/ByteLimitedInputStream.java

+ 23
- 6
src/main/java/org/cobbzilla/util/io/ByteLimitedInputStream.java Voir le fichier

@@ -18,6 +18,7 @@ public class ByteLimitedInputStream extends InputStream {

@Getter private long count = 0;
@Getter private long limit;
@Getter private boolean eos = false;

public double getPercentDone () { return ((double) count) / ((double) limit); }

@@ -27,24 +28,40 @@ public class ByteLimitedInputStream extends InputStream {
}

@Override public int read(byte[] b) throws IOException {
if (count >= limit) return -1;
if (eosOrLimitExceeded() == -1) return -1;
final int read = delegate.read(b);
if (read != -1) count += read;
incr(read);
return read;
}

@Override public int read(byte[] b, int off, int len) throws IOException {
if (count >= limit) return -1;
if (eosOrLimitExceeded() == -1) return -1;
final int read = delegate.read(b, off, len);
if (read != -1) count += read;
incr(read);
return read;
}

@Override public int read() throws IOException {
if (count >= limit) return -1;
if (eosOrLimitExceeded() == -1) return -1;
final int read = delegate.read();
if (read != -1) count++;
incr(read);
return read;
}

public int eosOrLimitExceeded() throws IOException{
if (count >= limit) {
if (!eos) throw new IOException("cannot continue reading: stream is larger than " + limit + " bytes");
return -1;
}
return 0;
}

public void incr(int read) {
if (read == -1) {
eos = true;
} else {
count += read;
}
}

}

Chargement…
Annuler
Enregistrer