为什么要花这么长时间从Android的Google驱动器下载PDF文件?

问题描述 投票:0回答:1

我正在尝试使用以下代码从Google驱动器下载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循环中的每个迭代下载一个大型文件,但仅下载2个大型文件需要2650迭代!任何想法如何解决这个问题?

android performance google-drive-api google-drive-android-api
1个回答
0
投票

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

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

(我加了强调)这里的期望未达到现实的可能原因:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.