How to save file from website to sdcard

前端 未结 3 1357
轻奢々
轻奢々 2020-11-28 05:33

Does anyone know how to save a file from a webserver(local host) to the sdcard through wifi?

I am doing xml parsing to my application and for that I have to downloa

3条回答
  •  庸人自扰
    2020-11-28 06:01

    You can use this method to download a file from the internet to your SD card:

    public void DownloadFromUrl(String DownloadUrl, String fileName) {
    
       try {
               File root = android.os.Environment.getExternalStorageDirectory();               
    
               File dir = new File (root.getAbsolutePath() + "/xmls");
               if(dir.exists()==false) {
                    dir.mkdirs();
               }
    
               URL url = new URL(DownloadUrl); //you can write here any link
               File file = new File(dir, fileName);
    
               long startTime = System.currentTimeMillis();
               Log.d("DownloadManager", "download begining");
               Log.d("DownloadManager", "download url:" + url);
               Log.d("DownloadManager", "downloaded file name:" + fileName);
    
               /* Open a connection to that URL. */
               URLConnection ucon = url.openConnection();
    
               /*
                * Define InputStreams to read from the URLConnection.
                */
               InputStream is = ucon.getInputStream();
               BufferedInputStream bis = new BufferedInputStream(is);
    
               /*
                * Read bytes to the Buffer until there is nothing more to read(-1).
                */
               ByteArrayBuffer baf = new ByteArrayBuffer(5000);
               int current = 0;
               while ((current = bis.read()) != -1) {
                  baf.append((byte) current);
               }
    
    
               /* Convert the Bytes read to a String. */
               FileOutputStream fos = new FileOutputStream(file);
               fos.write(baf.toByteArray());
               fos.flush();
               fos.close();
               Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
    
       } catch (IOException e) {
           Log.d("DownloadManager", "Error: " + e);
       }
    
    }
    

    You need to add the following permissions to your AndroidManifest.xml:

    
    
    
    
    

提交回复
热议问题