Android的爪哇 - 如何从URL下载的zip文件? [英] Android Java - How to download zip file from URL?

查看:246
本文介绍了Android的爪哇 - 如何从URL下载的zip文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨林决策,这就需要你从我的Dropbox下载一些文件的新项目。我添加了一个名为DownloadFile新的类,它有code下载文件。出于某种原因,应用程序崩溃,当我点击下载。谢谢你。

Hey Im making a new project which requires you to download some files from my Dropbox. I added a new class called DownloadFile which has the code to download a file. For some reason the app crashes when I click download. Thanks.

继承人的DownloadFile:

Heres the DownloadFile:

    package com.Matt7262.download.app;

    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    //Chat bot library
    import org.alicebot.ab.Chat;
    import org.alicebot.ab.Bot;

    import android.view.View;
    import android.widget.Button;
    import android.os.Environment;
    import android.widget.TextView;
    import android.widget.Toast;

    import java.io.InputStream;
    import java.net.URL;
    import java.io.DataInputStream;
    import java.io.DataOutputStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import android.widget.ProgressBar;
    import java.net.URL;
    import java.net.URLConnection;
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.os.Environment;
    import android.view.View.OnClickListener;

    public class DownloadFile extends ActionBarActivity{

    public void updateProgress(int currentSize, int totalSize)
    {
        Toast.makeText(getApplicationContext(), "Loading Files...",
                Toast.LENGTH_SHORT).show();
    }

    public void Download()
    {
        try {
            //set the download URL, a url that points to a file on the internet
            //this is the file to be downloaded
            URL url = new URL("https://dl.dropboxusercontent.com/shz/9cyfz0b45mj6szr/7pBuupNz3N/xecta?token_hash=AAEs9cDFswt98D1IhLnab4dHwhwh5z2Lmhq_N6H-2M0LWg&top_level_offset=6");

            //create the new connection
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            //set up some things on the connection
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);

            //and connect!
            urlConnection.connect();

            //set the path where we want to save the file
            //in this case, going to save it on the root directory of the
            //sd card.
            File SDCardRoot = Environment.getExternalStorageDirectory();
            //create a new file, specifying the path, and the filename
            //which we want to save the file as.
            File file = new File(SDCardRoot,"hello.zip");

            //this will be used to write the downloaded data into the file we created
            FileOutputStream fileOutput = new FileOutputStream(file);

            //this will be used in reading the data from the internet
            InputStream inputStream = urlConnection.getInputStream();

            //this is the total size of the file
            int totalSize = urlConnection.getContentLength();
            //variable to store total downloaded bytes
            int downloadedSize = 0;

            //create a buffer...
            byte[] buffer = new byte[1024];
            int bufferLength = 0; //used to store a temporary size of the buffer

            //now, read through the input buffer and write the contents to the file
            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                //add the data in the buffer to the file in the file output stream (the file on the sd card
                fileOutput.write(buffer, 0, bufferLength);
                //add up the size so we know how much is downloaded
                downloadedSize += bufferLength;
                //this is where you would do something to report the prgress, like this maybe
                updateProgress(downloadedSize, totalSize);

            }
            //close the output stream when done
            fileOutput.close();

            //catch some possible errors...
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    }

MainActivity:

MainActivity:

package com.Matt7262.download.app;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
//Chat bot library
import org.alicebot.ab.Chat;
import org.alicebot.ab.Bot;

import android.view.View;
import android.widget.Button;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;

import android.os.AsyncTask;

public class MainActivity extends ActionBarActivity {

    TextView input;
    String dPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download";
    private DownloadFile df;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    //EditText mEdit = (EditText)findViewById(R.id.editText1);

    public void buttonOnClick(View v)
    {
        input = (TextView) findViewById(R.id.editText1);

        String dbPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/Ab";

        Button button=(Button) v;

        //Creating bot
        String botname="xecta";
        String path= dbPath;
        Bot xecta = new Bot(botname, path);

        Chat chatSession = new Chat(xecta);

        String request = input.getText().toString();
        String response = chatSession.multisentenceRespond(request);
        ((Button) v).setText(response);
    }

    public void onClickDownload(View view)
    {
        df.Download();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /*public void updateProgress(int currentSize, int totalSize)
    {
        Toast.makeText(getApplicationContext(), "Retrieving Files...",
                Toast.LENGTH_SHORT).show();
    }/*

    /*public void Download()
    {
        try {
            //set the download URL, a url that points to a file on the internet
            //this is the file to be downloaded
            URL url = new URL("https://dl.dropboxusercontent.com/shz/9cyfz0b45mj6szr/7pBuupNz3N/xecta?token_hash=AAEs9cDFswt98D1IhLnab4dHwhwh5z2Lmhq_N6H-2M0LWg&top_level_offset=6");

            //create the new connection
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            //set up some things on the connection
            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);

            //and connect!
            urlConnection.connect();

            //set the path where we want to save the file
            //in this case, going to save it on the root directory of the
            //sd card.
            File SDCardRoot = Environment.getExternalStorageDirectory();
            //create a new file, specifying the path, and the filename
            //which we want to save the file as.
            File file = new File(SDCardRoot,"hello.zip");

            //this will be used to write the downloaded data into the file we created
            FileOutputStream fileOutput = new FileOutputStream(file);

            //this will be used in reading the data from the internet
            InputStream inputStream = urlConnection.getInputStream();

            //this is the total size of the file
            int totalSize = urlConnection.getContentLength();
            //variable to store total downloaded bytes
            int downloadedSize = 0;

            //create a buffer...
            byte[] buffer = new byte[1024];
            int bufferLength = 0; //used to store a temporary size of the buffer

            //now, read through the input buffer and write the contents to the file
            while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                //add the data in the buffer to the file in the file output stream (the file on the sd card
                fileOutput.write(buffer, 0, bufferLength);
                //add up the size so we know how much is downloaded
                downloadedSize += bufferLength;
                //this is where you would do something to report the prgress, like this maybe
                updateProgress(downloadedSize, totalSize);

            }
            //close the output stream when done
            fileOutput.close();

         //catch some possible errors...
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/


}

我觉得这是我走出的logcat的:

I think this is all I got out of the logcat:

<一个href=\"https://dl.dropboxusercontent.com/u/258218351/Screen%20Shot%202014-04-14%20at%208.43.50%20PM.png\"相对=nofollow> logcat的

推荐答案

您在声明 DownloadFile 对象,但不进行初始化。

You are declaring DownloadFile object but not initializing it.

private DownloadFile df;
df.Download(); // Throws NPE

不要忘了初始化。

Don't forget to initialize it.

private DownloadFile df = new DownloadFile();
df.Download();

编辑:

现在你初始化对象,避免了NPE,但这个时候,你得到一个 NetworkOnMainThreadException 。 Honeycomb版本之后,Android版不允许你做的主线程网络操作。您可以使用的AsyncTask 来克服这一点。

Now you initialised the object and avoided NPE but this time you are getting a NetworkOnMainThreadException. After Honeycomb version, Android does not allow you to do network operations on main thread. You can use an AsyncTask to overcome this.

这篇关于Android的爪哇 - 如何从URL下载的zip文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆