Ben
Ben

Reputation: 62356

How to get file size of http file path

I'm using the below code to download files from a remote location via http. Some assets are not fully downloading and appear to be corrupt. It looks to be about 5% of the time. I'm thinking it'd be good to ensure I've downloaded the full file by getting the file size in advance and comparing it to what I've downloaded to be sure nothing was missed.

Through some google searches and looking at the objects I'm already working with I don't see an obvious way to obtain this file size. Can someone point me in the right direction?

HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setInstanceFollowRedirects(true);

InputStream is = con.getInputStream();
file = new File(destinationPath+"."+remoteFile.getExtension());

BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file.getAbsolutePath()));
while ((i = bis.read()) != -1) {
   bos.write(i);
}
bos.flush();
bis.close();

Upvotes: 1

Views: 280

Answers (3)

Ankur Lathi
Ankur Lathi

Reputation: 7836

You can use InputStream#available() method.

It returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.

FileInputStream fis = new FileInputStream(destinationPath+"."+remoteFile.getExtension());
System.out.println("Total file size to read (in bytes) : "+ fis.available());

Upvotes: 0

Ian Roberts
Ian Roberts

Reputation: 122364

con.getContentLength() may give you what you want, but only if the server provided it as a response header. If the server used "chunked" encoding instead of providing a Content-Length header then the total length is not available up-front.

Upvotes: 3

Song Gao
Song Gao

Reputation: 666

Check out the getContentLength() method here HttpURLConnection that inherits from URLConnection.

Upvotes: 1

Related Questions