安卓:下载文件并保存在SD卡上 [英] Android: downloading a file and saving on sd card

查看:269
本文介绍了安卓:下载文件并保存在SD卡上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正试图创建一个应用程序下载到SD卡上的文件,这是我的code:


 公共类MainActivity延伸活动{    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);
        新主题(新的Runnable接口(){
            公共无效的run(){                                Log.i(step0,它从这里开始);
                的URLConnection URLConnection的= NULL;
                // TODO自动生成方法存根
                尝试{
                    //获取网址
                    Log.i(步骤1.1,获取URL);
                    网址URL =新的URL(http://people.opera.com/howcome/2005/ala/sample.pdf);
                    Log.i(步1.2,捕获的URL);
                    URLConnection的= url.openConnection();
                    Log.i(步1.3,捕获的URL);                    urlConnection.connect();
                    Log.i(第1步,获取网址);                    //指定路径和文件名
                    文件SD卡= Environment.getExternalStorageDirectory();
                    档案文件=新的文件(SD卡,filename.pdf);
                    Log.i(第2步,指定路径和文件名);                    // preparing下载
                    FileOutputStream中fileOutput =新的FileOutputStream(文件);
                    为InputStream的InputStream = urlConnection.getInputStream();                    字节[]缓冲区=新的字节[1024];
                    INT BufferLength中= 0;
                    Log.i(步骤3,preparing下载);
                    //下载
                    而(量(bufferLength = inputStream.read(缓冲液))大于0){
                        fileOutput.write(缓冲液,0,BufferLength中);
                    }
                    fileOutput.close();
                    Log.i(第4步,下载);                }赶上(MalformedURLException的E){
                        e.printStackTrace();
                }赶上(IOException异常五){
                        e.printStackTrace();
                }
            }
          })。开始();
    }
    @覆盖
    公共布尔onCreateOptionsMenu(菜单菜单){
        //充气菜单;如果是present这增加了项目操作栏。
        。getMenuInflater()膨胀(R.menu.main,菜单);
        返回true;
    }    @覆盖
    公共布尔onOptionsItemSelected(菜单项项){
        //处理动作栏项目点击这里。操作栏会
        //自动处理上点击主页/向上按钮,只要
        //你在AndroidManifest.xml中指定一个父活动。
        INT ID = item.getItemId();
        如果(ID == R.id.action_settings){
            返回true;
        }
        返回super.onOptionsItemSelected(项目);
    }
}

在清单文件权限:

 <使用许可权的android:NAME =android.permission.WRITE_EXTERNAL_STORAG​​E/>
<使用许可权的android:NAME =android.permission.WRITE_SYNC_SETTINGS/>
<使用许可权的android:NAME =android.permission.INTERNET对/>

我的日志文件:

  09-11 16:27:27.835:D / JDWP(5892):sendBufferedRequest:LEN = 0X47
09-11 16:27:27.865:W /资产(5892):AssetManager - > addDefaultAssets CIP路径不exsit!
09-11 16:27:27.920:V / PhoneWindow(5892):DecorView setVisiblity:知名度= 4
09-11 16:27:27.921:I / step0(5892):它从这里开始
09-11 16:27:27.922:I /步骤1.1(5892):获取URL
09-11 16:27:27.923:I /步1.2(5892):捕获的网址
09-11 16:27:27.924:I /步1.3(5892):捕获的网址
09-11 16:27:27.935:D / libc的,NetBSD的(5892)的getaddrinfo:people.opera.com从代理没有结果
09-11 16:27:27.937:我/的System.out(5892):[CDS] [DNS]无法解析主机people.opera.com:没有与主机名关联的地址
09-11 16:27:27.937:W / System.err的(5892)的java.net.UnknownHostException:无法解析主机people.opera.com:没有与主机名关联的地址
09-11 16:27:27.938:W / System.err的(5892):在java.net.InetAddress.lookupHostByName(InetAddress.java:439)
09-11 16:27:27.938:W / System.err的(5892):在java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
09-11 16:27:27.938:W / System.err的(5892):在java.net.InetAddress.getAllByName(InetAddress.java:214)
09-11 16:27:27.938:W / System.err的(5892):在libcore.net.http.HttpConnection<&初始化GT;(HttpConnection.java:70)
09-11 16:27:27.939:W / System.err的(5892):在libcore.net.http.HttpConnection<&初始化GT;(HttpConnection.java:50)
09-11 16:27:27.939:W / System.err的(5892):在libcore.net.http.HttpConnection $ Address.connect(HttpConnection.java:340)
09-11 16:27:27.939:W / System.err的(5892):在libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
09-11 16:27:27.939:W / System.err的(5892):在libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
09-11 16:27:27.939:W / System.err的(5892):在libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
09-11 16:27:27.939:W / System.err的(5892):在libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
09-11 16:27:27.939:W / System.err的(5892):在libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
09-11 16:27:27.939:W / System.err的(5892):在libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
09-11 16:27:27.939:W / System.err的(5892):在libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
09-11 16:27:27.940:W / System.err的(5892):在com.android.installapp.MainActivity $ 1.run(MainActivity.java:53)
09-11 16:27:27.940:W / System.err的(5892):在java.lang.Thread.run(Thread.java:838)
09-11 16:27:27.940:W / System.err的(5892):libcore.io.GaiException:产生的原因的getaddrinfo失败:EAI_NODATA(不与主机名关联的地址)
09-11 16:27:27.941:W / System.err的(5892):在libcore.io.Posix.getaddrinfo(本机方法)
09-11 16:27:27.941:W / System.err的(5892):在libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:59)
09-11 16:27:27.941:W / System.err的(5892):在java.net.InetAddress.lookupHostByName(InetAddress.java:405)
09-11 16:27:27.941:W / System.err的(5892):14 ...更多
09-11 16:27:27.941:W / System.err的(5892):libcore.io.ErrnoException:产生的原因的getaddrinfo失败:ENETUNREACH(网络无法访问)
09-11 16:27:27.942:W / System.err的(5892):17 ...更多
09-11 16:27:27.960:V / PhoneWindow(5892):DecorView setVisiblity:知名度= 0
09-11 16:27:28.064:D / libEGL(5892):加载/system/lib/egl/libEGL_mali.so
09-11 16:27:28.072:D / libEGL(5892):加载/system/lib/egl/libGLESv1_CM_mali.so
09-11 16:27:28.079:D / libEGL(5892):加载/system/lib/egl/libGLESv2_mali.so
09-11 16:27:28.183:D / OpenGLRenderer(5892):启用调试模式0
09-11 16:27:28.186:V / InputMethodManager(5892):onWindowFocus:空softInputMode = 32 =首次真正标志=#1810100
09-11 16:27:28.187:V / InputMethodManager(5892):启动输入:$ com.android.internal.policy.impl.PhoneWindow {DecorView VE 413fb9c0 .... - [R ..... ID 0,0- 480854} IC = NULL t​​ba=android.view.inputmethod.EditorInfo@4141e938 controlFlags =#104
09-11 16:27:28.282:V / InputMethodManager(5892):启动输入:绑定结果= {InputBindResult空com.android.inputmethod.latin / .LatinIME#47}
09-11 16:27:28.286:V / InputMethodManager(5892):onWindowFocus:空softInputMode = 32 =第一假标志=#1810100
09-11 16:27:28.290:V / PhoneWindow(5892):DecorView setVisiblity:知名度= 0
09-11 16:27:28.401:W / IInputConnectionWrapper(5892):showStatusIcon上的非活动InputConnection

我试着在互联网上搜索,但我无法来解决这个problem.It没有下载文件。
任何人都可以请帮助?


解决方案

试试这个:

  {尝试
        //设置下载网址,指向的文件在互联网上的网址
        //这是要下载的文件
        网址URL =新的URL(http://somewhere.com/some/webhosted/file);        //创建新的连接
        HttpURLConnection类的URLConnection =(HttpURLConnection类)url.openConnection();        //设置一些东西连接
        urlConnection.setRequestMethod(GET);
        urlConnection.setDoOutput(真);        //并连接!
        urlConnection.connect();        //设置路径,我们要保存的文件
        //在这种情况下,将其保存在的根目录
        //SD卡。
        文件SDCardRoot = Environment.getExternalStorageDirectory();
        //创建一个新的文件,指定路径和文件名
        //这是我们要保存的文件。
        档案文件=新的文件(SDCardRootsomefile.ext);        //这将用于下载的数据写入到我们创建的文件
        FileOutputStream中fileOutput =新的FileOutputStream(文件);        //这将在从因特网读取数据被用于
        为InputStream的InputStream = urlConnection.getInputStream();        //这是文件的总大小
        INT总计TOTALSIZE = urlConnection.getContentLength();
        //变量来存储下载的总字节
        INT downloadedSize = 0;        //创建一个缓冲区...
        字节[]缓冲区=新的字节[1024];
        INT BufferLength中= 0; //用于存储缓冲器的临时尺寸        //现在,读通过输入缓冲器和内容写入到文件
        而(量(bufferLength = inputStream.read(缓冲液))大于0){
                //在缓冲区中的文件输出流中的数据添加到该文件(该文件的SD卡上
                fileOutput.write(缓冲液,0,BufferLength中);
                //加起来的大小,所以我们知道有多少下载
                downloadedSize + = BufferLength中;
                //这是你会做一些汇报prgress,这样也许
                的UpdateProgress(downloadedSize,总计TOTALSIZE);        }
        完成后//关闭输出流
        fileOutput.close();//捕捉一些可能出现的错误...
}赶上(MalformedURLException的E){
        e.printStackTrace();
}赶上(IOException异常五){
        e.printStackTrace();
}

Was trying to create an application to download a file on SD card, here is my code.:


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Thread(new Runnable() {
            public void run() {

                                Log.i("step0","it starts here");
                URLConnection urlConnection = null;
                // TODO Auto-generated method stub
                try {
                    //fetching the URL
                    Log.i("step 1.1","getting the url");
                    URL url = new URL("http://people.opera.com/howcome/2005/ala/sample.pdf");
                    Log.i("step 1.2","captured the url");                
                    urlConnection = url.openConnection();
                    Log.i("step 1.3","captured the url");    

                    urlConnection.connect();
                    Log.i("step 1","fetching the URL");

                    //specifying path and file name 
                    File sdcard = Environment.getExternalStorageDirectory();
                    File file = new File(sdcard, "filename.pdf");
                    Log.i("step 2","specifying path and file name");

                    //Preparing for download
                    FileOutputStream fileOutput = new FileOutputStream(file);
                    InputStream inputStream = urlConnection.getInputStream();

                    byte[] buffer = new byte[1024];
                    int bufferLength = 0;
                    Log.i("step 3","Preparing for download");


                    //Downloading 
                    while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
                        fileOutput.write(buffer, 0, bufferLength);
                    }
                    fileOutput.close();
                    Log.i("step 4","Downloading");

                } catch (MalformedURLException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                }     
            }
          }).start();


    }


    @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);
    }
}

Permissions in Manifest file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS"/>
<uses-permission android:name="android.permission.INTERNET"/>

My log file:

09-11 16:27:27.835: D/jdwp(5892): sendBufferedRequest : len=0x47
09-11 16:27:27.865: W/asset(5892): AssetManager-->addDefaultAssets CIP path not exsit!
09-11 16:27:27.920: V/PhoneWindow(5892): DecorView setVisiblity: visibility = 4
09-11 16:27:27.921: I/step0(5892): it starts here
09-11 16:27:27.922: I/step 1.1(5892): getting the url
09-11 16:27:27.923: I/step 1.2(5892): captured the url
09-11 16:27:27.924: I/step 1.3(5892): captured the url
09-11 16:27:27.935: D/libc-netbsd(5892): getaddrinfo: people.opera.com NO result from proxy 
09-11 16:27:27.937: I/System.out(5892): [CDS][DNS]Unable to resolve host "people.opera.com": No address associated with hostname
09-11 16:27:27.937: W/System.err(5892): java.net.UnknownHostException: Unable to resolve host "people.opera.com": No address associated with hostname
09-11 16:27:27.938: W/System.err(5892):     at java.net.InetAddress.lookupHostByName(InetAddress.java:439)
09-11 16:27:27.938: W/System.err(5892):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
09-11 16:27:27.938: W/System.err(5892):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
09-11 16:27:27.938: W/System.err(5892):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
09-11 16:27:27.939: W/System.err(5892):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
09-11 16:27:27.939: W/System.err(5892):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
09-11 16:27:27.939: W/System.err(5892):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
09-11 16:27:27.939: W/System.err(5892):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
09-11 16:27:27.939: W/System.err(5892):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
09-11 16:27:27.939: W/System.err(5892):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
09-11 16:27:27.939: W/System.err(5892):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
09-11 16:27:27.939: W/System.err(5892):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
09-11 16:27:27.939: W/System.err(5892):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:81)
09-11 16:27:27.940: W/System.err(5892):     at com.android.installapp.MainActivity$1.run(MainActivity.java:53)
09-11 16:27:27.940: W/System.err(5892):     at java.lang.Thread.run(Thread.java:838)
09-11 16:27:27.940: W/System.err(5892): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
09-11 16:27:27.941: W/System.err(5892):     at libcore.io.Posix.getaddrinfo(Native Method)
09-11 16:27:27.941: W/System.err(5892):     at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:59)
09-11 16:27:27.941: W/System.err(5892):     at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
09-11 16:27:27.941: W/System.err(5892):     ... 14 more
09-11 16:27:27.941: W/System.err(5892): Caused by: libcore.io.ErrnoException: getaddrinfo failed: ENETUNREACH (Network is unreachable)
09-11 16:27:27.942: W/System.err(5892):     ... 17 more
09-11 16:27:27.960: V/PhoneWindow(5892): DecorView setVisiblity: visibility = 0
09-11 16:27:28.064: D/libEGL(5892): loaded /system/lib/egl/libEGL_mali.so
09-11 16:27:28.072: D/libEGL(5892): loaded /system/lib/egl/libGLESv1_CM_mali.so
09-11 16:27:28.079: D/libEGL(5892): loaded /system/lib/egl/libGLESv2_mali.so
09-11 16:27:28.183: D/OpenGLRenderer(5892): Enabling debug mode 0
09-11 16:27:28.186: V/InputMethodManager(5892): onWindowFocus: null softInputMode=32 first=true flags=#1810100
09-11 16:27:28.187: V/InputMethodManager(5892): START INPUT: com.android.internal.policy.impl.PhoneWindow$DecorView{413fb9c0 V.E..... R.....ID 0,0-480,854} ic=null tba=android.view.inputmethod.EditorInfo@4141e938 controlFlags=#104
09-11 16:27:28.282: V/InputMethodManager(5892): Starting input: Bind result=InputBindResult{null com.android.inputmethod.latin/.LatinIME #47}
09-11 16:27:28.286: V/InputMethodManager(5892): onWindowFocus: null softInputMode=32 first=false flags=#1810100
09-11 16:27:28.290: V/PhoneWindow(5892): DecorView setVisiblity: visibility = 0
09-11 16:27:28.401: W/IInputConnectionWrapper(5892): showStatusIcon on inactive InputConnection

I tried searching on the internet, but I am unable to solve this problem.It isn't downloading the file. Can anyone please help?

解决方案

Try this:

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("http://somewhere.com/some/webhosted/file");

        //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,"somefile.ext");

        //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();
}

这篇关于安卓:下载文件并保存在SD卡上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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