Skip to content

Instantly share code, notes, and snippets.

@TrevorPage
Created April 12, 2015 12:29
Show Gist options
  • Save TrevorPage/925bd8b3fe749ccd994b to your computer and use it in GitHub Desktop.
Save TrevorPage/925bd8b3fe749ccd994b to your computer and use it in GitHub Desktop.
SizedFileInputStream
// Your package here
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import com.dropbox.sync.android.DbxException;
import com.dropbox.sync.android.DbxFile;
/**
* Wraps an InputStream obtained from a standard File or DbxFile.
* Allows the total file size to be known before reading any data.
*/
public class SizedFileInputStream extends InputStream {
private final FileInputStream mStream;
private long mFileSize;
public SizedFileInputStream(File file) throws FileNotFoundException {
mStream = new FileInputStream(file);
mFileSize = file.length();
}
public SizedFileInputStream(DbxFile file) throws DbxException, IOException {
mStream = file.getReadStream();
mFileSize = file.getInfo().size;
}
@Override
public int read() throws IOException {
int read = mStream.read();
return read;
}
@Override
public int read(byte[] buffer) throws IOException {
int read = mStream.read(buffer);
return read;
}
@Override
public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
int read = mStream.read(buffer, byteOffset, byteCount);
return read;
}
@Override
public int available() throws IOException {
return mStream.available();
}
@Override
public void close() throws IOException {
this.mStream.close();
}
@Override
public boolean markSupported() {
return mStream.markSupported();
}
@Override
public void mark(int readLimit) {
mStream.mark(readLimit);
}
@Override
public long skip(long byteCount) throws IOException {
return mStream.skip(byteCount);
}
public long getFileSize() {
return mFileSize;
}
}
@TrevorPage
Copy link
Author

This is from a project where I needed to pass an InputStream around based on a File, but classes reading from that InputStream want to know the total size of the file so that an accurate progress indicator can be displayed. The Dropbox stuff may not be relevant to you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment