【发布时间】:2014-03-08 13:12:31
【问题描述】:
我们正在准备一个应用程序,我们必须在其中从服务器下载一堆数据.. 所以,我们决定对整个数据进行 Zip 压缩并从服务器下载..
它也可以正常工作..我们可以完全下载文件...
我的问题是:
( 1 ) 我们的文件正在完全下载,但它显示 Archieve 格式未知或已损坏。 如何在 Android 中使用 HttpConnection 下载文件而不损坏..?
( 2 ) 如果我们使用WinRar Tools(Alt+R) 修复下载的文件,那么新的 Zip 可以正常工作。
所以,我的问题是How to Repair a zip File Programmatically in Android..?
从服务器下载 zip 的代码:
HttpURLConnection connection = null;
URL url = null;
try
{
url = new URL(zipPath);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(connectionTimeOutSec * 1000);
connection.setReadTimeout(connectionReadOutSec * 60 * 1000);
connection.setInstanceFollowRedirects(false);
}
catch (MalformedURLException e)
{
e.printStackTrace();
return "";
} catch (IOException e)
{
e.printStackTrace();
return "";
}
if(firsttime == 0)
{
firsttime = 1;
if(file.exists()){
downloaded = (int) file.length();
connection.setRequestProperty("Range", "bytes="+(file.length())+"-");
);
}
else
{
file.mkdirs();
file.delete();
}
}
else {
connection.setRequestProperty("Range", "bytes=" + (file.length()) + "-");
}
connection.setDoInput(true);
connection.setDoOutput(true);
if(file.exists()){
TotalByes = (int) file.length();
}
file = null;
Log.d("Total Value Received", "" + connection.getContentLength());
if(connection.getContentLength() > 0)
TotalByes += connection.getContentLength();
try {
in = new BufferedInputStream(connection.getInputStream());
fos = (downloaded == 0)? new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/EduTab"+"/"+zipfilePath): new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/EduTab"+"/"+zipfilePath,true);
}
catch (IOException e) {
if(connection != null)
{
connection.disconnect();
}
e.printStackTrace();
return "";
}
bout = new BufferedOutputStream(fos, 1024);
byte[] data = new byte[1024];
int x = 0;
try {
while ((x = in.read(data, 0, 1024)) >= 0) {
bout.write(data, 0, x);
downloaded += x;
}
} catch (IOException e) {
if(connection != null)
{
connection.disconnect();
}
e.printStackTrace();
return "";
}
对于下载 Zip 文件,我们参考了此链接:
Resume http file download in java
任何进一步的帮助将不胜感激..
【问题讨论】: