嘿家伙有人可以告诉我为什么我不能将此文件保存到外部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 :(得分:2)
如果您在AndroidManifest.xml
文件中没有以下权限,则此操作将失败:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
确保将它们放在顶级<manifest>
标记中,而不是指定活动的<application>
标记。
答案 1 :(得分:0)
我之前遇到过类似的问题。事实证明,在调用Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
检查文件资源管理器中是否存在该目录的绝对路径。如果没有,则通过adb shell
创建,然后再试一次。这解决了我的问题,但它可能不一定能解决你的问题,试试吧!