2

Why I cannot save this file to the external sd? Can you check over my code?

 public void Download()
  {
      try {
            //this is the file you want to download from the remote server
            String path ="http://mozilla.cdn.leaseweb.com/firefox/releases/4.0.1/win32/en-US/Firefox%20Setup%204.0.1.exe";
            //this is the name of the local file you will create
            String targetFileName;
                boolean eof = false;
            URL u = new URL(path);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();
            
            //String svto = Environment.getExternalStorageState().toString();
            File path1 = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_PICTURES);

            path1.mkdirs();
            FileOutputStream f = new FileOutputStream(new File(path1+"/fox.exe"));
                InputStream in = c.getInputStream();
                byte[] buffer = new byte[1024];
                int len1 = 0;
                while ( (len1 = in.read(buffer)) !=  -1 ) {
                f.write(buffer,0, len1);
                         }
            f.close();
            } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            } catch (ProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

  }
peterh
  • 11,875
  • 18
  • 85
  • 108
cruisx
  • 31
  • 1
  • 4

2 Answers2

2

This operation will fail if you don't have the following permissions in your AndroidManifest.xml file:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />

Make sure to put them within the top-level <manifest> tag, not the <application> tag where your activities are specified.

Jordan
  • 6,083
  • 3
  • 23
  • 30
0

I had a problem similar to this before. It turned out that I had to manually create the directory first on the SD card before calling code such as Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

Check if the absolute path exists on your file explorer for that directory. If it doesn't, then create it via adb shell and then give it a try again. This solved my problem, but it may not necessarily solve yours, give it a try though!

Hakan Ozbay
  • 4,639
  • 2
  • 22
  • 28
  • That is how im doing it, still does not seem to work =/. And im testing on both my phone and emulator, same result. – cruisx Apr 29 '11 at 22:20