3

I have tried to download a file from url and save it to memory cart, but I cant understand what is my wrong, my code is

URL url = new URL(imageURL);
        File file = new File(fileName);

        long startTime = System.currentTimeMillis();
        Log.d("ImageManager", "download begining");
        Log.d("ImageManager", "download url:" + url);
        Log.d("ImageManager", "downloaded file name:" + fileName);
        URLConnection ucon = url.openConnection();
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        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.close();
        Log.d("ImageManager", "download ready in"
                        + ((System.currentTimeMillis() - startTime) / 1000)
                        + " sec");

but i found the following error in my console

12-27 14:50:01.302: D/EXCEPTION GET:(8062): java.io.FileNotFoundException: /my.jpg (Read-only file system)

Actually i dont know what can i do, anyone help please.

Pritom
  • 1,294
  • 8
  • 19
  • 37

1 Answers1

3

The problem is with your path to save the file , fileName shouldn't start with a / and apply this modification to your code .

File extStore = Environment.getExternalStorageDirectory();
File file = new File(extStore, fileName);

You should check media availability before trying to save .

Rick
  • 1,124
  • 9
  • 13
  • please look at this `http://stackoverflow.com/questions/8687849/how-can-i-download-a-file-to-my-downloads-folder-android` – Pritom Dec 31 '11 at 11:34