且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

安卓:下载文件并保存在SD卡上

更新时间:2023-09-27 22:49:16

试试这个:

  {尝试
        //设置下载网址,指向的文件在互联网上的网址
        //这是要下载的文件
        网址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();
}