Skip to content

Instantly share code, notes, and snippets.

@develjs
Created November 3, 2017 14:11
Show Gist options
  • Save develjs/5e808f7a70fe240f2a3e23ba07aea05d to your computer and use it in GitHub Desktop.
Save develjs/5e808f7a70fe240f2a3e23ba07aea05d to your computer and use it in GitHub Desktop.
Partial InputStream for Android
package com.github.develjs;
import android.support.annotation.NonNull;
import java.io.IOException;
import java.io.InputStream;
public class PartInputStream extends InputStream {
private int subAvailable = 0; // <= 0, offset of stop-position relatively from end of main stream
private InputStream stream;
public PartInputStream(@NonNull InputStream stream, int offset, int length) throws Exception {
// super();
this.stream = stream;
int available = stream.available();
offset = Math.min(offset, available);
subAvailable = Math.min(offset + length, available) - available;
this.skip(offset);
}
@Override
public int available() throws IOException {
return stream.available() + subAvailable;
}
@Override
public void close() throws IOException {
stream.close();
super.close();
}
@Override
public int read() throws IOException {
if (available()>0)
return stream.read();
else
return -1;
}
@Override
public int read(@NonNull byte[] buffer, int byteOffset, int byteCount) throws IOException {
return stream.read(buffer, byteOffset, Math.min(byteCount, available()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment