从文件下载中写出百分比?

时间:2012-07-12 07:55:36

标签: java android android-file

我有我的文件下载方法,我是从教程中做到的:

InputStream input;
try
{
    URL url = new URL(strURL);
    input = url.openStream();
    byte[] buffer = new byte[1500];

    File OpenGuideFolder = new File("/sdcard/MyFiles/");
    OpenGuideFolder.mkdirs();

    OutputStream output = new FileOutputStream(OpenGuideFolder.toString() + "/" + id + "_" + pos + "_normal.png");
    try
    {
        int bytesRead = 0;
        while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0)
        {
            output.write(buffer, 0, bytesRead);

            for(int i =0;i<buffer.length;i++)
            {
                Log.i("buffer.length", Integer.toString(buffer.length));
            }
        }
    }
    finally
    {
        output.close();
        buffer = null;
    }
}
catch (Exception e)
{
    Log.i("Download Pictures Exception",e.toString());
}

您能否建议我获取下载文件的当前百分比?

2 个答案:

答案 0 :(得分:6)

您可以使用AsyncTask,只需在打开连接后获取文件长度:

URLConnection conection = url.openConnection();
                conection.connect();
                // getting file length
                int lenghtOfFile = conection.getContentLength();

并使用以下内容发布您的进度:publishProgress(""+(int)((total*100)/lenghtOfFile));

您可以在此link

上找到完整的教程
   /**
     * Background Async Task to download file
     * */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread
         * Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(progress_bar_type);
        }

        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();
                // getting file length
                int lenghtOfFile = conection.getContentLength();

                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                // Output stream to write file
                OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress(""+(int)((total*100)/lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
       }

        /**
         * After completing background task
         * Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);

            // Displaying downloaded image into image view
            // Reading image path from sdcard
            String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
            // setting downloaded into image view
            my_image.setImageDrawable(Drawable.createFromPath(imagePath));
        }

    }

答案 1 :(得分:1)

URLConnection connection = url.openConnection();
connection.connect();

int length = connection.getContentLength();

将为您提供要下载的文件的大小。 然后,您只需要更新下载内容的当前大小。

您将找到更多代码here