2011-04-29 117 views
3

嘿傢伙有人能告訴我爲什麼我不能保存這個文件到外部SD?你能檢查我的代碼嗎?Android保存到外部SD卡?

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(); 
     } 

    } 
+0

你得到的錯誤是什麼? – OceanBlue 2011-04-29 20:56:32

+0

在這種情況下,很高興看到錯誤和/或堆棧跟蹤。 – Devunwired 2011-04-29 22:07:06

回答

2

,如果你沒有在你的AndroidManifest.xml文件中的下列權限此操作將失敗:

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

確保將它們放在頂層內<manifest>標籤,而不是<application>標籤哪裏你的活動被指定。

+0

和android.permission.INTERNET以及 – Devunwired 2011-04-29 21:20:11

+0

不錯的調用,編輯。 – Jordan 2011-04-29 21:33:16

+0

我已經添加了這些,仍然無法使它去到外部。我可以將文件保存到數據/數據,但用戶無法訪問它。 – cruisx 2011-04-29 21:47:49

0

我以前有類似的問題。事實證明,我必須在SD卡上首先手動創建目錄,然後才能調用代碼,如Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

檢查文件資源管理器中是否存在該目錄的絕對路徑。如果沒有,請通過adb shell創建它,然後再試一次。這解決了我的問題,但它可能不一定解決你的問題,但試試!

+0

這就是即時通訊的做法,似乎仍然不起作用= /。而我的手機和模擬器即時測試,結果相同。 – cruisx 2011-04-29 22:20:56