Android Java-如何从URL下载zip文件?

Android Java-如何从URL下载zip文件?,第1张

概述嘿,我正在制作一个新项目,要求您从我的Dropbox下载一些文件.我添加了一个名为DownloadFile的新类,该类具有下载文件的代码.由于某些原因,当我单击下载时,应用程序崩溃.谢谢.继承人DownloadFile:packagecom.Matt7262.download.app;importandroid.support.v7.app.Actio

嘿,我正在制作一个新项目,要求您从我的DropBox下载一些文件.我添加了一个名为Downloadfile的新类,该类具有下载文件的代码.由于某些原因,当我单击下载时,应用程序崩溃.谢谢.

继承人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();        }    }    }

主要活动:

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 libraryimport 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中获得的所有信息:

logcat

解决方法:

您在声明Downloadfile对象,但未对其进行初始化.

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

不要忘记初始化它.

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

编辑:

现在,您初始化了该对象并避免了NPE,但是这次您遇到了networkonmainthreadException.在Honeycomb版本之后,AndroID不允许您在主线程上进行网络 *** 作.您可以使用AsyncTask来克服此问题.

总结

以上是内存溢出为你收集整理的Android Java-如何从URL下载zip文件?全部内容,希望文章能够帮你解决Android Java-如何从URL下载zip文件?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1076580.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存