2
I have the following code that downloads file from the internet
public boolean copiar(){
boolean teste = false;
try
{
String local = System.getProperty("user.dir") +"\\PDV.jar";;
String archive = "https://github.com/cbcarlos07/PDV-client/blob/master/PDV.jar";
InputStream in = new URL(archive).openStream();
OutputStream out = new FileOutputStream( local, false );
long expectedBytes = in.available(); // This is the number of bytes we expected to copy..
long totalBytesCopied = 0; // This will track the total number of bytes we've copied
byte[] buf = new byte[1024];
int len = 0;
System.out.println("Total: "+expectedBytes);
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
totalBytesCopied += len;
System.out.println("Len: "+len);
System.out.println("totalCopiado: "+totalBytesCopied);
double total = ( totalBytesCopied * 100 ) / expectedBytes;
double percentual = ( totalBytesCopied / expectedBytes ) * 100;
System.out.println( total );
System.out.println(percentual+"%");
}
System.out.println("");
in.close();
out.close();
teste = true;
}
catch(Exception ex)
{
ex.printStackTrace();
}
return teste;
}
It works, but I would like to know before, which file size to make a progress indicator
Know the total file, how much has been downloaded and how many more to download, to make up the download time
An alternative would be read the header
Content-Length
, but this URL returns the headerTransfer-Encoding: chunked
, and in such cases theContent-Length
is not returned (see more about this here, here and here). So I guess in this case there really is no way...– hkotsubo