Jake Miller Jake Miller - 10 days ago 8
Java Question

Figuring out the size of an InputStream

I'm currently getting an input stream using Amazon's S3 storage like below:

public static InputStream getResourceAsStream(String fileKey) {
AmazonS3 s3Client = new AmazonS3Client(new ProfileCredentialsProvider());
return s3Client.getObject(new GetObjectRequest(bucketName, fileKey)).getObjectContent();
}


The files I'm dealing with are .mp4 videos. I'm attempting to stream the video using Range-Requests to allow for fast forwarding and rewinding for the end user. My streaming was working fine when I was using regular
File
objects, but now I'm receiving a stream from Amazon S3 instead of using a file saved on a local machine.

How can I figure out the length of this stream? Before, I did this:

Long length = Files.size(filepath);


But now this does not work as I do not have a file saved directly on the machine running the Java code. Is there any way to figure out the length of the
InputStream
?

nos nos
Answer

You can't get the length of an InputStream unless you read it from start to end and count the number of bytes you've read yourself.

You can get the length of an S3Object though:

public static InputStream getResourceAsStream(String fileKey) {
    AmazonS3 s3Client = new AmazonS3Client(new ProfileCredentialsProvider());
    S3Object obj = s3Client.getObject(new GetObjectRequest(bucketName, fileKey));
    long length = obj.getObjectMetadata().getInstanceLength();
    //use length
    return obj.getObjectContent();
}
Comments