java - 写出文件下载的百分比?

标签 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());
}

你能建议我一种获取当前下载文件百分比的方法吗?

最佳答案

您可以使用 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));
        }

    }

关于java - 写出文件下载的百分比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11447366/

相关文章:

java - 难以使用自定义适配器填充 GridView

java - 如何将文件存储在我的 Android 模拟设备上,然后从我的程序中访问它?

java - Android应用程序备份和恢复?

java - Eclipse:如何查找继承字段的引用(不是

java - 为什么显式类型参数应该用菱形代替?

android - 在不打开 Android 应用程序的情况下执行操作

java - 无法查看 fragment 内接收的短信

android - 如何检查文件是否存在且内容相同

java - 'alternatives' 真的比符号链接(symbolic link)和 $PATH 更适合管理 JDK 吗?