【问题标题】:Why it takes so long to download PDF file from google drive in android?为什么从 android 的谷歌驱动器下载 PDF 文件需要这么长时间?
【发布时间】:2020-02-07 15:36:17
【问题描述】:

我正在尝试使用以下代码从谷歌驱动器下载 PDF 文件:

try {
            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.connect();

            if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK){
                Log.v(TAG,"server returned http " + urlConnection.getResponseCode()
                        + urlConnection.getResponseMessage());
            }
            else{
                Log.v(TAG + "downloading" ,"server returned http " + urlConnection.getResponseCode()
                        + urlConnection.getResponseMessage());
            }

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();
            int total = 0;

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            int i = 0;
            while((bufferLength = inputStream.read(buffer))!= -1 ) 
            {
                i+=1;
                Log.v(TAG + "downloading","downloading mega #"+i);
                total += bufferLength;
                fileOutputStream.write(buffer, 0, bufferLength);
            }

            fileOutputStream.close();
            inputStream.close();
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (MalformedURLException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }

如代码所示,while循环中每次迭代下载一个mega文件,但是2650次迭代只下载2个mega文件!!!!!! 知道如何解决这个问题吗?

【问题讨论】:

    标签: android performance google-drive-api google-drive-android-api


    【解决方案1】:

    我不能确切地说,为什么会这样,但引用 javadoc Inputstream#read(byte[]):

    读取的字节数最多等于b的长度。

    (重点由我添加)

    此处期望与现实不符的可能原因:

    • MEGABYTE 设置为错误的大小(应为 1000000)
    • 连接速度不够高
    • 其他障碍,“读取”无法读取每个循环的完整缓冲区大小


    您可以检查每个循环读取的字节数,但它可能对您没有太大帮助。

    【讨论】:

    • - 我将 MEGABYTE 定义为等于 1024 * 1024 - 当我从普通浏览器下载它时,它需要更快,所以我认为这不是连接速度问题 - 实际上可能是“读取”无法读取每个循环的完整缓冲区大小。知道如何解决这个问题吗?
    • 哦,好吧,这个定义也有效。不,遗憾的是我不知道如何解决这个问题。与浏览器下载相比,下载是否也需要更长的时间?
    猜你喜欢
    • 2011-11-12
    • 2018-09-20
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多