Java – how do I retrieve the size of a file from a URL download (using an HTTP connection)?
•
Java
I am using a project to download files using an HTTP connection I display a horizontal progress bar with progress bar status during download
....... try { InputStream myInput = urlconnect.getInputStream(); BufferedInputStream buffinput = new BufferedInputStream(myInput); ByteArrayBuffer baf = new ByteArrayBuffer(capacity); int current = 0; while((current = buffinput.read()) != -1) { baf.append((byte) current); } File outputfile = new File(createRepertory(app,0),Filename); FileOutputStream myOutPut = new FileOutputStream(outputfile); myOutPut.write(baf.toByteArray()); ... }
I know the size of my file in advance, so I need to retrieve the size in the download (in my while block) Therefore, I can determine the status of the progress bar
progressBarStatus = ((int) downloadFileHttp(url,app) * 100)/sizefile;
Long downloadfilehttp (..,..) Is the name of my function
I've tried by using outputFile Length to retrieve it, but its value is "1". Maybe this is the number of files I want to download
Update 1
Solution
Asynctask may be your perfect solution:
private class DownloadFileTask extends AsyncTask<URL,Integer,Long> { protected Long doInBackground(URL... urls) { Url url = urls[0]; //connect to url here ....... try { InputStream myInput = urlconnect.getInputStream(); BufferedInputStream buffinput = new BufferedInputStream(myInput); ByteArrayBuffer baf = new ByteArrayBuffer(capacity); int current = 0; while((current = buffinput.read()) != -1) { baf.append((byte) current); //here you can send data to onProgressUpdate publishProgress((int) (((float)baf.length()/ (float)sizefile) * 100)); } File outputfile = new File(createRepertory(app,Filename); FileOutputStream myOutPut = new FileOutputStream(outputfile); myOutPut.write(baf.toByteArray()); ... } protected void onProgressUpdate(Integer... progress) { //here you can set progress bar in UI thread progressBarStatus = progress; }
}
Start the asynctask call in your method
new DownloadFileTask().execute(url);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码