簡體   English   中英

從HttpResponse將JPEG寫入Java / Android中的文件

[英]Writing JPEG from HttpResponse to file in Java/Android

我無法從http服務器將.jpg文件寫入android設備的文件系統。 我使用以下代碼:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;

public void processResult(HttpResponse response) {

    if(response.getStatusLine().getStatusCode() != 401){

        if(response != null){
            File file = new File(parent, myLocation);
            try {
               file.getParentFile().mkdirs();
               file.createNewFile();
               HttpEntity entity = response.getEntity();
               FileOutputStream fileOS  = new FileOutputStream(file);
               entity.writeTo(fileOS);
               entity.consumeContent();
               fileOS.flush();
               fileOS.close();
               success  =   true;
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }                   
        }
    }
}

jpg文件為73369字節。 如果在成功=真行上停止調試器,則可以看到Entity.getContentLength()為73369,這是正確的。 但是,file.length()在大多數情況下為我提供0,有時在7770或介於兩者之間的某個尺寸。

如果我在文件瀏覽器中檢查了Android設備,則顯示的長度為7 KB或更短。

我嘗試了其他方法來處理InputStream,但沒有成功:

我嘗試獲取一個字節數組並將其寫入文件,但這給了我一個空的字節數組:

private static void writeToFile(File file, byte[] bs) throws IOException{
       file.getParentFile().mkdirs();
       file.createNewFile();

       FileOutputStream fileOS  = new FileOutputStream(file);
       fileOS.write(bs);
       fileOS.flush();
       fileOS.close();
}

我開始嘗試將輸入流寫到文件中,但這得到了相同的結果

public static final void streamToFile(File file, InputStream stream) throws IOException {
   file.createNewFile();

   FileOutputStream fileOS  = new FileOutputStream(file);

   byte[] buffer = new byte[1024];
   int bytesRead;      

   while ((bytesRead = stream.read(buffer)) != -1)
    {
       fileOS.write(buffer, 0, bytesRead);
    }
    stream.close();
    fileOS.flush();
    fileOS.close();
}

輸入流似乎很好,但我無法將其放入文件中。 有人對此有所幫助嗎?

謝謝!

上面顯示的代碼是正確的。 問題在於,在讀取流完成之前已關閉連接。 忽略這是因為對字符串(JSON)的get請求很好(較小的響應大小)。

暫無
暫無

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

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