如何在android中正确下载带有java代码的zip文件?

如何在android中正确下载带有java代码的zip文件?,android,download,zip,Android,Download,Zip,我尝试将zip文件下载到android,然后解压缩zip文件。我调试代码时发现一个有趣的问题:下载的zip文件比原始文件大一点。winrar无法解压缩下载的zip文件。据说下载的文件以错误结束。(我网站上的zip文件还可以。我试着用IE下载。效果很好。) 以下是我的代码: public void download(final String url, final String savePath, final String saveName) { new Thread(new Runnabl

我尝试将zip文件下载到android,然后解压缩zip文件。我调试代码时发现一个有趣的问题:下载的zip文件比原始文件大一点。winrar无法解压缩下载的zip文件。据说下载的文件以错误结束。(我网站上的zip文件还可以。我试着用IE下载。效果很好。) 以下是我的代码:

public void download(final String url, final String savePath, final String saveName) {
    new Thread(new Runnable() {
        public void run() {
            try {
                sendMessage(FILE_DOWNLOAD_CONNECT);
                URL sourceUrl = new URL(url);
                URLConnection conn = sourceUrl.openConnection();
                conn.connect();
                InputStream inputStream = conn.getInputStream();

                int fileSize = conn.getContentLength();

                File savefilepath = new File(savePath);
                if (!savefilepath.exists()) {
                    savefilepath.mkdirs();
                }
                File savefile = new File(savePath+saveName);
                if (savefile.exists()) {
                    savefile.delete();
                }
                savefile.createNewFile();

                FileOutputStream outputStream = new FileOutputStream(
                    savePath+saveName, true);

                byte[] buffer = new byte[1024];
                int readCount = 0;
                int readNum = 0;
                int prevPercent = 0;
                while (readCount < fileSize && readNum != -1) {
                    readNum = inputStream.read(buffer);
                    if (readNum > -1) {
                        outputStream.write(buffer);

                        readCount = readCount + readNum;

                        int percent = (int) (readCount * 100 / fileSize);
                        if (percent > prevPercent) {
                            sendMessage(FILE_DOWNLOAD_UPDATE, percent,
                                readCount);

                            prevPercent = percent;
                        }
                    }
                }
                outputStream.flush();
                outputStream.close();
                inputStream.close();
                //Thread.sleep(50);
                sendMessage(FILE_DOWNLOAD_COMPLETE, savePath);

            } catch (Exception e) {
                sendMessage(FILE_DOWNLOAD_ERROR, e);
            }
        }
    }).start();
}
public void下载(最终字符串url、最终字符串保存路径、最终字符串保存名称){
新线程(newrunnable()){
公开募捐{
试一试{
sendMessage(文件下载连接);
URL sourceUrl=新URL(URL);
URLConnection conn=sourceUrl.openConnection();
连接();
InputStream InputStream=conn.getInputStream();
int fileSize=conn.getContentLength();
File savefilepath=新文件(savePath);
如果(!savefilepath.exists()){
savefilepath.mkdirs();
}
File savefile=新文件(savePath+saveName);
if(savefile.exists()){
savefile.delete();
}
savefile.createNewFile();
FileOutputStream outputStream=新FileOutputStream(
savePath+saveName,true);
字节[]缓冲区=新字节[1024];
int readCount=0;
int readNum=0;
整数百分比=0;
while(readCount-1){
outputStream.write(缓冲区);
readCount=readCount+readNum;
整数百分比=(整数)(读计数*100/文件大小);
如果(百分比>上一个百分比){
sendMessage(文件下载更新,百分比,
读取计数);
百分比=百分比;
}
}
}
outputStream.flush();
outputStream.close();
inputStream.close();
//睡眠(50);
sendMessage(文件下载完成,保存路径);
}捕获(例外e){
sendMessage(文件下载错误,e);
}
}
}).start();
}

有人知道这个问题吗?

当您读入缓冲区时,您正在将整个缓冲区写入输出流:

outputStream.write(buffer);
您应该只写入已填充的缓冲区部分:

outputStream.write(buffer, 0, readNum);
特别是对于网络下载,不能保证调用
inputStream.read(buffer)
将填充缓冲区(即使文件中有超过1024个字节)。

公共类下载扩展了活动{
公共静态最终整型对话框\u下载\u进度=0;
private ProgressDialog mProgressDialog;
公共字符串app_name;
公共字符串路径;
/**在首次创建活动时调用*/
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
app_name=“test.rar”;
urlpath=”https://www.abc.com/download/“+应用程序名称;
如果(android.os.Environment.getExternalStorageState().equals
(android.os.Environment.MEDIA_-MOUNTED)
{        
startDownload();
}
其他的
{
Toast.makeText(getApplicationContext(),“未找到SD卡,请插入SD卡并重试”,Toast.LENGTH_SHORT).show();
}
}
私有void startDownload(){
新建DownloadFileAsync().execute(urlpath);
}
@凌驾
受保护的对话框onCreateDialog(int id){
开关(id){
案例对话框\u下载\u进度:
mProgressDialog=新建进度对话框(此);
设置消息(“下载更新…”);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_水平);
mProgressDialog.setCancelable(假);
mProgressDialog.setUndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.show();
返回mProgressDialog;
违约:
返回null;
}
}
类DownloadFileAsync扩展AsyncTask{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
showDialog(对话框下载进度);
}
@凌驾
受保护的字符串背景(字符串…aurl){
试一试{
URL URL=新URL(urlpath.toString());//您给定的URL。
HttpURLConnection c=(HttpURLConnection)url.openConnection();
c、 setRequestMethod(“GET”);
c、 设置输出(真);
c、 connect();//连接在此完成。!
int lenghtOfFile=c.getContentLength();
Log.d(“下载更新”,“文件长度:+lenghtOfFile”);
String PATH=Environment.getExternalStorageDirectory()+“/download/”;
File File=new File(PATH);//PATH=/mnt/sdcard/download/
如果(!file.exists()){
mkdirs()文件;
}
文件输出文件=新文件(文件、应用程序名称);
FileOutputStream fos=新的FileOutputStream(outputFile);
InputStream=c.getInputStream()/
字节[]缓冲区=新字节[1024];
int len1=0;
长总计=0;
而((len1=is.read(buffer))!=-1){
总+=len1;
出版进度(“+(int)((总计*100)/长度文档));
fos.write(缓冲区,0,len1);//写入FileOutputStream。
}
fos.flush();
fos.close();
is.close();
}捕获(例外e){}
返回null;
}
受保护的void onProgressUpdate(字符串…进度){
Log.d(“下载更新”,pr
public class Download extends Activity {
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;

private ProgressDialog mProgressDialog;
    public String app_name ;
    public String urlpath ;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);



app_name="test.rar";        
    urlpath = "https://www.abc.com/download/"+ app_name;
    if (android.os.Environment.getExternalStorageState().equals
            (android.os.Environment.MEDIA_MOUNTED))
    {        
        startDownload();
    }

    else
    {
         Toast.makeText(getApplicationContext(), "SD Card not found,Insert SD card and try again", Toast.LENGTH_SHORT).show();
    }

}

private void startDownload() {

    new DownloadFileAsync().execute(urlpath);
}
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Downloading Updates..");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(false);
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.setMax(100);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
    }
}
class DownloadFileAsync extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected String doInBackground(String... aurl) {


        try {


            URL url = new URL(urlpath.toString()); // Your given URL.

            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect(); // Connection Complete here.!


            int lenghtOfFile = c.getContentLength();


            Log.d("Downloading Updates", "Lenght of file: " + lenghtOfFile);

            String PATH = Environment.getExternalStorageDirectory() + "/download/";

            File file = new File(PATH); // PATH = /mnt/sdcard/download/

            if (!file.exists()) {
                file.mkdirs();
            }
            File outputFile = new File(file, app_name);           
            FileOutputStream fos = new FileOutputStream(outputFile);



            InputStream is = c.getInputStream(); /

            byte[] buffer = new byte[1024];
            int len1 = 0;
            long total = 0;
            while ((len1 = is.read(buffer)) != -1) {
                total += len1;
                publishProgress(""+(int)((total*100)/lenghtOfFile));

                fos.write(buffer, 0, len1); // Write In FileOutputStream.
            }
            fos.flush();
            fos.close();
            is.close();
        } catch (Exception e) {}
        return null;

    }
    protected void onProgressUpdate(String... progress) {
         Log.d("Downloading Updates",progress[0]);
         mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String unused) {
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        finish();
    }
}
}