簡體   English   中英

InputStream 寫入 OutputStream 花費的時間太長 Android

[英]InputStream writing to OutputStream taking too long Android

我正在嘗試從我的 Web API 獲取圖像,並將它們填充到回收視圖中。 我通過 Web API 獲取圖片 - 我使用 Retrofit 2.0 來使用 API。 圖像已被壓縮(它們的大小范圍為 100 - 300kb)。 我面臨的問題是將輸入流的內容寫入輸出流的 while 循環需要很長時間 - 我發現這個循環每個圖像需要 7 到 11 秒之間的任何時間。 這是獲取圖片的代碼:

        if (postList.size() > 0) {
            for (HousePostViewModel model : postList) {
                Response<ResponseBody> pictureCall = service.getHousePostImage("Bearer " + sharedPreferences.getString("authorization_token", ""), model.getHousePostID(), currentActivity.getResources().getString(R.string.homenet_client_string)).execute();
                if (pictureCall.isSuccessful()) {
                    try {
                        InputStream inputStream = null;
                        FileOutputStream outputStream = null;
                        File profileFile = new File(currentActivity.getExternalCacheDir() + File.separator + generateRandomString()+"tempImage3.jpg");
                        inputStream = new BufferedInputStream(pictureCall.body().byteStream());
                        outputStream = new FileOutputStream(profileFile);
                        int c;
                        Log.i("START", "Starting to read the image");
                        long timeInMS = System.currentTimeMillis();
                        //This is the loop, where images take long to write to outputstream
                        while ((c = inputStream.read()) != -1) {
                            outputStream.write(c);
                        }
                        Picture picture = new Picture(profileFile);
                        pictureList.add(picture);
                        long finish = System.currentTimeMillis();
                        long finalTime = finish - timeInMS;
                        Log.i("END", "Finished Reading file in " +finalTime+" ms");
                        inputStream.close();
                        outputStream.close();
                    } catch (Exception error) {

                    }
                } else {
                    errorString += pictureCall.errorBody().string();
                }
            }
        }
    }
} else {
    errorString += postCall.errorBody().string();
}

你們建議我嘗試什么,或者做什么? 或者是否有另一種從 API 獲取圖像數據的方法?

while ((c = inputStream.read()) != -1) {
    outputStream.write(c);
}

使用緩沖 I/O。 希望我每次發帖都能得到一筆錢:

char[] buffer = new char[8192];
int count;
while ((count = inputStream.read(buffer)) > 0)
{
    outputStream.write(buffer, 0, count);
}

...你應該在FileOutputStream周圍包裹一個BufferedOutputStream ,因此:

outputStream = new BufferedOutputStream(new FileOutputStream(profileFile));

您還需要創建Picture之前關閉流。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM