Android: downloading a file and saving on sd card

落花浮王杯 提交于 2019-12-18 13:36:49

问题


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?


回答1:


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



回答2:


If you download file from URL then try below code with folder name and file name

public void DownloadFile(String strUrl, String folderName, String fileName) {
    try {
        File dir = new File(Environment.getExternalStorageDirectory() + "/"
                + folderName);
        if (dir.exists() == false) {
            dir.mkdirs();
        }

        URL url = new URL(strUrl);
        File file = new File(dir, fileName);

        URLConnection ucon = url.openConnection();
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(20000);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.flush();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


来源:https://stackoverflow.com/questions/25785609/android-downloading-a-file-and-saving-on-sd-card

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!