Skip to content

Instantly share code, notes, and snippets.

@mikeblum
Created September 8, 2016 20:26
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikeblum/ebb976fb396af70f372c642de22656ba to your computer and use it in GitHub Desktop.
Save mikeblum/ebb976fb396af70f372c642de22656ba to your computer and use it in GitHub Desktop.
Calculate the size of an InputStream
package size_checker;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class SizeChecker {
private static final String SMALL_PDF = "small.pdf";
private static final String LARGE_PDF = "large.pdf";
public static void main(String[] args) {
long size = 0;
int chunk = 0;
long start = 0;
InputStream is = null;
File largeFile = new File(LARGE_PDF);
try {
start = System.currentTimeMillis();
is = new FileInputStream(largeFile);
byte[] buffer = new byte[1024];
while((chunk = is.read(buffer)) != -1){
size += chunk;
}
} catch (FileNotFoundException e) {
System.out.println("Failed to open file stream:" + e.getMessage());
} catch (IOException e) {
System.out.println("Failed to read from file stream:" + e.getMessage());
}finally{
if(is != null){
try {
is.close();
} catch (IOException e) {
System.out.println("Failed to close InputStream: " + e.getMessage());
}
}
long done = System.currentTimeMillis() - start;
System.out.println(String.format("took %d milliseconds", done));
}
System.out.println("size: " + size + " bytes");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment