Android saving to external SD card?
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_P开发者_运维问答ICTURES);
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();
}
}
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.
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!
精彩评论