2013-04-25 65 views
0

我的代碼有問題。我正在嘗試從網址保存PDF。 PDF在那裏,但其長度爲零。輸入流的長度是正確的。爲什麼不能正確保存PDF?保存來自InputStream的PDF

這是從流保存PDF的實際代碼:

public void createExternalStoragePrivateFile 
          (String name, String extension, InputStream is) { 
    // Create a path where we will place our private file on external 
    // storage. 
    File file = new File 
        (mContext.getExternalFilesDir(null), name +"."+extension); 

    try { 
     Log.d("", "before: " + file.getPath() + 
          " " + file.getTotalSpace() + " " + file.length()); 
     OutputStream os = new FileOutputStream(file); 
     byte[] data = new byte[is.available()]; 
     is.read(data); 
     os.write(data); 
     is.close(); 
     os.close(); 

     Log.d("","after: " + file.getPath() + 
           " " + file.getTotalSpace() + " " + file.length()); 
    } catch (IOException e) { 
     // Unable to create file, likely because external storage is 
     // not currently mounted. 
     Log.w("ExternalStorage", "Error writing " + file, e); 
    } 

輸出給了我這個(長度爲零之前和之後,但總的空間不爲零後爲什麼。長度爲零?

04-25 09:38:44.938: D/(4103): before: /storage/emulated/0/Android 
            /data/what.to.use.myapp/files/Lolpdf.pdf 0 0 

04-25 09:38:44.946: D/(4103): after: /storage/emulated/0/Android 
         /data/what.to.use.myapp/files/Lolpdf.pdf 14311309312 0 

回答

1

InputStream.available()方法不一定返回該文件的大小下載,它會返回一個可用而不做任何網絡調用,所以很可能會返回0。更好的辦法是分配一個小緩衝區,一個ð堅持讀書,直到你到達終點:

byte[] buffer = new byte[1024]; 
int len; 
while ((len = is.read(buffer)) != -1) { 
    os.write(buffer, 0, len); 
} 

這將是更多的內存效率,因爲它不要求你分配足夠的內存來保存你下載整個文件,它避免了available()方法這不會返回你期待的結果。

+0

+1 avaialble()不應該用於確定文件的長度 – 2013-04-25 08:19:07