views:

801

answers:

2

Hey,

I am using the following code to download a file from my server then write it to the root directory of the sd card, it all works fine:

package com.downloader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Environment;
import android.util.Log;

public class Downloader {

    public void DownloadFile(String fileURL, String fileName) {
        try {
            File root = Environment.getExternalStorageDirectory();
            URL u = new URL(fileURL);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();
            FileOutputStream f = new FileOutputStream(new File(root, fileName));

            InputStream in = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = in.read(buffer)) > 0) {
                f.write(buffer, 0, len1);
            }
            f.close();
        } catch (Exception e) {
            Log.d("Downloader", e.getMessage());
        }

    }
}

However, using Environment.getExternalStorageDirectory(); means that the file will always write to the root /mnt/sdcard. Is it possible to specify a certain folder to write the file to?

For example: /mnt/sdcard/myapp/downloads

Cheers

Eef

A: 

Try this instead. I've used it before in my own app...

String fileName = "test.txt";
File destinationFile = new File("/sdcard/myapp/downloads/" + fileName);    
InputStream in = c.getInputStream();
BufferedOutputStream buffer = new BufferedOutputStream(new FileOutputStream(destinationFile)); 
byte byt[] = new byte[1024]; 
int i; 

for (long l = 0L; (i = c.read(byt)) != -1; l += i ) {
    buffer.write(byt, 0, i); 
}

inputstream.close();               
buffer.close();
Ryan Berger
+5  A: 
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdcard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "filename");

FileOutputStream f = new FileOutputStream(file);
...
radek-k
Cheers mate, works a treat.
Eef
A minor fix: the last line should read FileOutputStream(file);
Vytautas Shaltenis
Good point.Fixed.
radek-k