11

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 download an xml file from localhost to the sdcard and then tag the parsing. I am stuck with downloading an xml file to the sd card. Please guide me on how to do this..

sealz
  • 5,348
  • 5
  • 40
  • 70
RAAAAM
  • 3,378
  • 19
  • 59
  • 108

3 Answers3

42

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:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
Sourav
  • 1,214
  • 14
  • 24
  • This is really great answer... one more question, do you know how to store file in invisible mode. (ie) storing file will never visible to user. – RAAAAM Mar 30 '11 at 04:33
  • Sorry, I don't have any idea about that. Perhaps [this post will help](http://stackoverflow.com/questions/1129644/how-to-make-a-file-hidden-in-android-sd-card) – Sourav Mar 30 '11 at 06:23
  • @HariRam : you may want to put or call this method in an `AsyncTask or in a new `Thread. In this way, the download process is hidden from the user. – Jayson Tamayo Dec 05 '11 at 06:41
  • @Selvin whats the problem with that while? – PureSpider Nov 19 '12 at 09:33
  • 4
    i don't like reading byte by byte just change it to some buffered version, next why are you reading whole stream to ByteArrayBuffer when you wana just write it to file(another stream) ... so better solution is `int count; byte[] buffer = new byte[8192]; while ((count = in.read(buffer)) > 0) out.write(buffer, 0, count);` – Selvin Nov 19 '12 at 09:45
  • for ease in understanding i added pictorial representation of the prog . Please look [link] (https://www.facebook.com/photo.php?fbid=10200943885226089&set=oa.504118742982929&type=1&theater) –  Apr 09 '13 at 08:59
  • @Sourav why do you need ACCESS_NETWORK_STATE and READ_PHONE_STATE to run this code? – Nikolai Samteladze May 13 '13 at 07:27
  • @Sourav i was able to download file but it is not taking as video file and when i am trying to open this file it says `Unable to find application to perform this action` how to make as a video not just a file – Kartheek Sarabu May 07 '14 at 11:06
  • @Kartheek To open a video file you need a Video Player / 3rd party app installed on your device....but that's beyond the subject of this post – Sourav May 07 '14 at 11:53
  • Sorry I got the answer. If I extend the file name to `.mp4` the downloaded file takes it as video file – Kartheek Sarabu May 07 '14 at 12:29
  • @delive what exactly were you trying to create? – Sourav Jul 01 '15 at 16:49
  • good answer. But now ByteArrayBuffer is deprecated , so you can find replacement code [here](https://stackoverflow.com/questions/32138739/bytearraybuffer-missing-in-sdk23) – Harsh Sanghani Nov 21 '17 at 06:42
  • Cannot import ByteArrayBuffer. I think new sdk versions removed that. Please update your answer compatible to latest version. – Dinith Rukshan Kumara May 26 '18 at 07:05
1

The Sourav's answer is OK, but for large file sizes you should implement it on a new thread; because while downloading, the main thread is busy for downloading the file. If the waiting time be more that expected the system will generate "Not responding" error.

In order to do that you can use "TaskAsync" or "IntentService"

Saman Pour
  • 576
  • 4
  • 8
0

I prefer to build soap server and make a call from app to server and by that receiving XML. Or maybe you could just make an URL which generates XML and that just parse URL directly.

Try to read more on this LINK

Hopefully I have answer the question. Otherwise would be pleased to help, but I need more detailed functionality description.

M.V.
  • 1,662
  • 8
  • 32
  • 55
  • Thank you, my issue is i want to save xml file which is residing from my local host server to sd card. Just to save. – RAAAAM Mar 29 '11 at 12:30
  • Hey, to do that, I suggest to just make a static PHP download script ([link](http://www.ryboe.com/tutorials/php-headers-force-download)) and than simply download from a URL do your phone where you set a path to SD card... – M.V. Mar 30 '11 at 08:42