做來電顯示歸屬地和查詢歸屬地功能的時候,需要從伺服器下載資料庫,
但是下載之後,查詢總是報錯database disk image is malformed (code 11)
開始以為是查詢語句不對,後來意識到,跟之前解析包時出現錯誤是一樣的問題,
下載過程中格式損壞了。
於是解決方案跟http://blog.csdn.net/jason0539/article/details/21742019採取了一樣的策略,
把每次讀取的數組縮小,代碼如下:
public class DownloadTask { /** * @param path * @param filePath儲存路徑 * @param progressDialog進度條 * @return * @throws Exception */ public static File getFile(String path,String filePath,ProgressDialog progressDialog) throws Exception{ URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(2000); connection.setRequestMethod("GET"); if(connection.getResponseCode() == 200){ int total = connection.getContentLength(); progressDialog.setMax(total); InputStream is = connection.getInputStream();//獲得socket輸入資料流 File file = new File(filePath); FileOutputStream fos = new FileOutputStream(file);//file輸出資料流 byte[] buffer = new byte[1024]; int len; int progress = 0; while((len = is.read(buffer)) != -1){ fos.write(buffer); progress += len; progressDialog.setProgress(progress); } fos.flush(); is.close(); fos.close(); connection.disconnect(); return file; } return null; }
把裡面這行裡的1024改小就可以避免損壞了,
byte[] buffer = new byte[1024];
由於總是錯,我甚至改成了
byte[] buffer = new byte[8];
這樣是沒錯了,但是有個弊端,下載變的很慢,下載的資料庫是16M的,奇慢無比,
臨時性這樣解決了。
作者:jason0539
微博:http://weibo.com/2553717707
部落格:http://blog.csdn.net/jason0539(轉載請說明出處)