2017-02-14 83 views
0

從服務器上下載文件後,我將文件保存到磁盤,但我相信它在保存在光盤上時會損壞。如果在Mac上使用chrome或使用其他方法下載相同的文件,則該文件會正常下載並讀取。腐敗似乎是在文件的保存過程中。我添加了代碼來幫助找出問題。該文件是一個css文件。Android - 保存文件時損壞

損壞: 讀取文件時會出現一些空白字符。我試過並且注意到的一個令人驚訝的事情是,如果我從4096中將BUFFER_SIZE減少到32,那麼這個文件不會被破壞,我不知道爲什麼。而且,減少BUFFER_SIZE可以減少空白/損壞的字符。

欣賞正確方向上的任何指針。由於

private static final int BUFFER_SIZE = 4096; 

// saves file to disk and returns the contents of the file. 
public static String downloadFile(Context context, String filePath, String destParent) { 
    String content = null; 
    StringBuilder sb = new StringBuilder(); 
    HttpURLConnection connection = null; 
    InputStream is = null; 
    FileOutputStream os = null; 
    String sUrl = Urls.makeWebAssetUrl(filePath); /// consider this my file URL 
    String destFile = getContextBaseDir(context) + (destParent != null ? File.separator + destParent : "") + File.separator + filePath; 

    try { 
     URL url = new URL(sUrl); 
     connection = (HttpURLConnection) url.openConnection(); 
     connection.connect(); 
     int responseCode = connection.getResponseCode(); 
     if (responseCode == HttpURLConnection.HTTP_OK) { 
      File outFile = new File(destFile); 
      if (!outFile.getParentFile().exists()) { 
       if (!outFile.getParentFile().mkdirs()) { 
        throw new RuntimeException("Unable to create parent directories for " + filePath); 
       } 
      } 

      is = connection.getInputStream(); 
      os = new FileOutputStream(outFile); 

      int bytesRead = 0; 
      byte[] buffer = new byte[BUFFER_SIZE]; 
      while ((bytesRead = is.read(buffer)) != -1) { 
       sb.append(new String(buffer, 0, bytesRead, DEFAULT_ENCODING)); 
       os.write(buffer); 
      } 
      content = sb.toString(); 
     } 
     else { 
      LogUtils.LOGW(TAG, responseCode + " while connecting to " + sUrl + ": " + connection.getResponseMessage()); 
     } 
    } catch(Exception e) { 
     LogUtils.LOGE(TAG, "Error while downloading " + sUrl, e); 
    } finally { 
     if (is != null) { 
      try { 
       is.close(); 
      } catch (IOException e) { 
       LogUtils.LOGE(TAG, "Error closing inputStream while downloading " + sUrl, e); 
      } 
     } 

     if (os != null) { 
      try { 
       os.flush(); 
      } catch (IOException e) { 
       LogUtils.LOGE(TAG, "Error flushing outputStream while downloading " + sUrl, e); 
      } 

      try { 
       os.close(); 
      } catch (IOException e) { 
       LogUtils.LOGE(TAG, "Error closing outputStream while downloading " + sUrl, e); 
      } 
     } 
    } 
    return content; 
} 

回答

0
os.write(buffer); 

的問題是在這裏。它應該是:

os.write(buffer, 0, bytesRead); 

我不知道爲什麼你積累在StringBuffer的內容並返回它作爲一個String。這不會擴展,在任何劇組中都是多餘的。去掉。

+0

非常感謝,這是問題所在。立即解決:) –